Reputation: 5047
I changed my whole app from "float" to decimal but in one point, I just cannot resolve this issue:
string a="9.02"
decimal d=Convert.ToDecimal(a);
It throws an exception, incorrect input string format
. Why?
Upvotes: 0
Views: 4667
Reputation: 98750
Convert.ToDecimal(string)
method uses CurrentCulture
by default. Here how it's implemented;
public static decimal ToDecimal(String value)
{
if (value == null)
return 0m;
return Decimal.Parse(value, CultureInfo.CurrentCulture);
}
Probably your CurrentCulture
's NumberDecimalSeparator
property is not .
and that's why this method throws FormatException
.
As an alternative, you can use InvariantCulture
(which it's NumberDecimalSeparator
is .
) as a second parameter in your Convert.ToDecimal(String, IFormatProvider)
method or you can Clone
your CurrentCulture
and set it's NumberDecimalSeparator
propert to dot.
string a = "9.02";
decimal d = Convert.ToDecimal(a, CultureInfo.InvariantCulture);
or
string a = "9.02";
var clone = (CultureInfo)CultureInfo.CurrentCulture.Clone();
clone.NumberFormat.NumberDecimalSeparator = ".";
decimal d = Convert.ToDecimal(a, clone);
Upvotes: 7