Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to decimal with format

Tags:

string

c#

decimal

I need convert a String to a decimal in C#, but this string have different formats.

For example:

"50085"

"500,85"

"500.85"

This should be convert for 500,85 in decimal. Is there is a simplified form to do this convertion using format?

like image 345
Daniel Gielow Junior Avatar asked May 11 '11 11:05

Daniel Gielow Junior


1 Answers

Try this code below:

string numValue = "500,85";
System.Globalization.CultureInfo culInfo = new System.Globalization.CultureInfo("fr-FR");
decimal decValue;
bool decValid = decimal.TryParse(numValue, System.Globalization.NumberStyles.Number, culInfo.NumberFormat, out decValue);
if (decValid)
{
    lblDecNum.Text = Convert.ToString(decValue, culInfo.NumberFormat);
}

Since I am giving a value of 500,85 I will assume that the culture is French and hence the decimal separator is ",". Then decimal.TryParse(numValue, System.Globalization.NumberStyles.Number, culInfo.NumberFormat,out decValue); will return the value as 500.85 in decValue. Similarly if the user is English US then change the culInfo constructor.

like image 70
Nisha_Roy Avatar answered Oct 20 '22 20:10

Nisha_Roy