如何在 C# 中将浮点字符串转换为 int
我有一个字符串:
string test = "19,95";
我不想将其转换为 int 。
我使用:
int num = Convert.Int32(test);
但是它会抛出 FormatException。并告诉我该字符串不是适合转换的字符串。
我的猜测是它与小数分隔符有关。
我该如何解决这个问题?
I have a string:
string test = "19,95";
and I wan't to convert it to an int.
I use:
int num = Convert.Int32(test);
However it throws an FormatException. And tells me that the string is not a proper string for conversion.
My guess is that it has to do with the decimal seperator.
How do i work around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
经测试&在职的。
为了完整起见:
[更新]
正如Rushyo在我下面的评论中正确指出的那样,这个示例是人为的,最佳实践方法是确定您正在使用哪种文化,以便获得正确的 CultureInfo 对象工作了。
然后,您可以在执行所有数字格式设置时使用该特定 CultureInfo 中的本地化 NumberFormatInfo。
Tested & working.
For completeness:
[Update]
As Rushyo correctly pointed out in my comments below, this example is contrived and the best practice approach is to identify which culture you are working with in order to get the correct CultureInfo object to work off of.
You can then utilize the localized NumberFormatInfo from that specific CultureInfo when doing all your numeric formatting.
如果您需要 19(舍去小数部分):
如果您需要 20(数学四舍五入):
If you need 19 (casting off the decimal part):
If you need 20 (mathematical rounding):
您希望从
"19,95"
获得什么整数? 1995 年? 19? 20?也许您应该首先将数字转换为双精度,然后按照对您的应用程序有意义的方向进行舍入或截断。
What integer would you expect to get from
"19,95"
? 1995? 19? 20?Perhaps you should convert the number to a double first, and then round or truncate in whichever direction makes sense for your application.
正如其他人已经提到的,您问题的主要问题是,您没有提供有关您期望的结果的任何信息,有些人还提出了文化问题(小数分隔符、千位分隔符)。所以我会做一个小小的总结:
As the others already mentioned the main problem of your question is, that you don't gave any information about what result you expect and some also brought up the problem with the Culture (decimal separator, thousand separator). So i will make a little sum up:
你确定要它是一个 int 吗?
这个数字是双倍的。
are you sure you want it to be an int?
this number is a double.