Share via


how to convert string with comma(",") to decimal and how to verify whether a decimal is good for "decimal(6,5)"

Question

Wednesday, March 12, 2014 3:03 PM

hi

    i'd like to ask how to convert string with comma(",") to decimal? i know i can use convert.todecimal? but sometimes i found it works for "3,5" to 3.5,but sometimes is it is "3.5" to 3.5 ,depends on pc of different users? is there a parameter to ensure the format is to use comma(","?

   another question is,is there is way to check whether the deciaml is good for the length of "decimal(6,5)"?

   thank u very much

best regards

martin

All replies (2)

Wednesday, March 12, 2014 3:34 PM ✅Answered

Try this:

string value;
decimal number;
NumberStyles style;
 
value = "3,5";
style = NumberStyles.Number;
number = Decimal.Parse(value, style);  
Console.WriteLine("'{0}' converted to {1}.", value, number);

 

Noam B.

Do not Forget to Vote as Answer/Helpful, please. It encourages us to help you...


Wednesday, March 12, 2014 5:45 PM ✅Answered

When you're parsing an input string from a format that does not depend on the user's settings, it is best to explicitly specify an IFormatProvider that does not use those settings.

NumberFormatInfo numberFormatWithComma = new NumberFormatInfo();
numberFormatWithComma.NumberDecimalSeparator = ",";
Console.WriteLine(decimal.Parse("3,5", numberFormatWithComma) / 2);

That will compute the same number for every user. (Console.WriteLine will then format the result with user-specific settings, though.)

Alternatively, you can use String.Replace to change "," to ".", and then parse the result with CultureInfo.InvariantCulture.  However, the NumberFormatInfo solution seems clearer to me.