Decimal Casting

牧云@^-^@ 提交于 2019-12-12 18:44:18

问题


I have a decimal number like this:

62.000,0000000

I need to cast that decimal into int; it will always have zero decimal numbers; so I wont loose any precision. What I want is this:

62.000

Stored on an int variable in c#.

I try many ways but it always give me an error, that the string isn't in the correct format, this is one of the ways i tryied:

int.Parse("62.000,0000000");

Hope you can help me, thanks.


回答1:


You need to parse it in the right culture. For example, the German culture uses "." as a group separator and "," as the decimal separator - so this code works:

CultureInfo german = new CultureInfo("de-DE");
decimal d = decimal.Parse("62.000,0000000", german);
int i = (int) d;

Console.WriteLine(i); // Prints 62000

Is that what you're after? Note that this will then fail if you present it with a number formatted in a different culture...

EDIT: As Reed mentions in his comment, if your real culture is Spain, then exchange "de-DE" for "es-ES" for good measure.




回答2:


You need to specify your culture correctly:

var ci = CultureInfo.CreateSpecificCulture("es-ES");
int value = (int) decimal.Parse("60.000,000000", ci);

If you do this, it will correctly convert the number.




回答3:


Why don't you just cast it to int instead of parsing?



来源:https://stackoverflow.com/questions/1971076/decimal-casting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!