Convert string to decimal, keeping fractions

NETQuestion picture NETQuestion · Nov 24, 2010 · Viewed 323.7k times · Source

I am trying to convert 1200.00 to decimal, but Decimal.Parse() removes .00. I've tried some different methods, but it always removes .00, except when I supply a fraction different than 0.

string value = "1200.00";

Method 1

 var convertDecimal = Decimal.Parse(value ,  NumberStyles.AllowThousands
       | NumberStyles.AllowDecimalPoint | NumberStyles.AllowCurrencySymbol);

Method 2

 var convertDecimal = Convert.ToDecimal(value);

Method 3

var convertDecimal = Decimal.Parse(value,
       NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture);

How can I convert a string containing 1200.00 to a decimal containing 1200.00?

Answer

Jon Skeet picture Jon Skeet · Nov 24, 2010

Hmm... I can't reproduce this:

using System;

class Test
{
    static void Main()        
    {
        decimal d = decimal.Parse("1200.00");
        Console.WriteLine(d); // Prints 1200.00
    }
}

Are you sure it's not some other part of your code normalizing the decimal value later?

Just in case it's cultural issues, try this version which shouldn't depend on your locale at all:

using System;
using System.Globalization;

class Test
{
    static void Main()        
    {
        decimal d = decimal.Parse("1200.00", CultureInfo.InvariantCulture);
        Console.WriteLine(d.ToString(CultureInfo.InvariantCulture));
    }
}