开发者

Convert "2.45" to decimal

I know this is the silliest question to ask. But really I'm having trouble to convert price(string) to decimal. Here is what I have tried

string s = "123.45";
decimal d = decimal.Parse(s, NumberStyles.AllowCurrencySymbol | NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint);

But I'm getting Format exce开发者_运维问答ption

Also tried

decimal num;
bool pass = decimal.TryParse("2.85", out num);

num comes out as 0.

Any help will be greatly appreciated.


Try specifying an invariant culture in which . is the decimal separator:

string s = "123.45";
decimal d = decimal.Parse(
    s, 
    NumberStyles.AllowCurrencySymbol | NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint, 
    CultureInfo.InvariantCulture
);

The Parse method uses the current thread culture to parse numbers. So if you are using some culture in which . is not the decimal separator (such as fr-FR for example) it won't work as it would expect the number to be 123,45 for instance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜