Advertisement
Advertisement


Convert string to decimal, keeping fractions


Question

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?

2014/03/07
1
69
3/7/2014 9:23:27 AM


I think your problem is when displaying the decimal, not the contents of it.

If you try

string value = "1200.00";
decimal d = decimal.Parse(s);
string s = d.ToString();

s will contain the string "1200".

However if you change your code to this

string value = "1200.00";
decimal d = decimal.Parse(s);
string s = d.ToString("0.00");

s will contain the string "1200.00" as you want it to do.

EDIT

Seems I'm braindead early in the morning today. I added the Parse statements now. However even my first code will output "1200.00", even if I expected it to output "1200". Seems like I'm learning something each day, and in this case obviously something that is quite basic.

So disregard this a an proper answer. We will probably need more code to identify your problem in this case.

2010/11/24

Hello i was have the same issue, but it is easly, just do this:

string cadena="96.23";

decimal NoDecimal=decimal.parse(cadena.replace(".",","))

I think this is beacuse the notation that accept C# on decimal numbers are with a ","

2015/08/18

The below code prints the value as 1200.00.

var convertDecimal = Convert.ToDecimal("1200.00");
Console.WriteLine(convertDecimal);

Not sure what you are expecting?

2010/11/24

The use of CultureInfo class worked for me, I hope help you.

    string value = "1200.00";
    CultureInfo culture = new CultureInfo("en-US");
    decimal result = Convert.ToDecimal(value, culture);
2018/06/05

Use this example

System.Globalization.CultureInfo culInfo = new System.Globalization.CultureInfo("en-GB",true);

decimal currency_usd = decimal.Parse(GetRateFromCbrf("usd"),culInfo);
decimal currency_eur = decimal.Parse(GetRateFromCbrf("eur"), culInfo);
2014/03/07

Source: https://stackoverflow.com/questions/4264736
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]