Reputation: 18257
Sounds easy but when I tried to achieve i'm stock about how is the formatter to make this conversion this are some examples of strings that i need to convert to decimal
00.24
48.34
01.24
Does anybody know how can i Accomplish this?? I tried like this
try
{
decimal x = Convert.ToDecimal("00.24", );
//Which formatter do I need to pass??
decimal x = Convert.ToDecimal("00.24", Formatter???);
}
Catch(Exception e)
{
throw new Exception()
}
But It doesn't work because the result it's 24D and i need 0.24D
Upvotes: 1
Views: 4342
Reputation: 39055
The result you're getting is because the dot .
is tretaed as a group (thousand) separator. the parser simply discards it, and doesn't check if the group sizes are right. So '20.100.200' or '1.2.3.4' would also get parsed as 20100200 and 1234.
This happens on many european cultures, like 'es'
You have to use any culture that doesn't consider a .
as a group separator, but as a decimal separator. CultureInfo.InvariantCulture
is one of the possible cultures (it has basically the same configuration of en-US).
Upvotes: 1
Reputation: 755457
Why not just use Decimal.Parse
decimal x = Decimal.Parse("00.24");
Console.WriteLine(x); // Prints: 00.24
Upvotes: 3
Reputation: 292695
I suspect your system culture is not English and has different number formatting rules. Try passing the invariant culture as the format provider:
decimal d = Convert.ToDecimal("00.24", CultureInfo.InvariantCulture);
You could also use Decimal.Parse
:
decimal d = Decimal.Parse("00.24", CultureInfo.InvariantCulture);
Upvotes: 5