I need to accept 3 decimal data formats in my app:
I cannot assume that one format will be used in particular situation. What I need is get a decimal value from a string no matter in which format it's given.
Is there a smart way to do this?
I was trying to use
var culture = CultureInfo.CreateSpecificCulture("en-US");
but this doesn't seem to work on wp7.
So far I've done this:
public static class Extensions
{
public static decimal toDecimal(this string s)
{
decimal res;
int comasCount=0;
int periodsCount=0;
foreach (var c in s)
{
if (c == ',')
comasCount++;
else if (c == '.')
periodsCount++;
}
if (periodsCount > 1)
throw new FormatException();
else if(periodsCount==0 && comasCount > 1)
throw new FormatException();
if(comasCount==1)
{
// pl-PL
//parse here
}else
{
//en-US
//parse here
}
return res;
}
}
Converting a string to a decimal value or decimal equivalent can be done using the Decimal. TryParse() method. It converts the string representation of a number to its decimal equivalent.
Converts the string representation of a number to its Decimal equivalent using the specified culture-specific format information.
To convert a Decimal value to its string representation using a specified culture and a specific format string, call the Decimal. ToString(String, IFormatProvider) method.
ToString() is a method in C# that is called on decimal values. It converts a numeric value that is a decimal to a string.
Try using var culture = new CultureInfo("en-US");
to create the culture. Passing that culture to decimal.Parse
or decimal.TryParse
will parse the text appropriately for each culture.
Now, keep in mind that each culture may parse the text without failure but not parse it the way it's represented for the original culture. For example decimal.TryParse("1000,314", NumberStyles.Number, new CultureInfo("en-US"), out result)
will result success and 1000314m, not 1000.314m. Whereas decimal.TryParse("1000,314", NumberStyles.Number, new CultureInfo("fr-FR"), out result)
will result in 1000.314m.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With