简体   繁体   English

从字符串解析浮点数

[英]parse float from string

I have some problem with parsing float value from string. 我从字符串解析浮点值有一些问题。
Problem is with decimal part of value, here is example: 问题在于值的小数部分,这是示例:

var tmp = "263148,21";
var ftmp = float.Parse(tmp); //263148.219

I tried some other values, but I don't figured out, from what reason are some decimal values incorrect. 我尝试了其他一些值,但我不知道是什么原因导致某些十进制值不正确。

This doesn't have anything to do with the comma in the OP's code - instead, this question is about a float value not accurately representing a real number. 这与OP的代码中的逗号没有任何关系-而是,这个问题是关于float值不能准确表示实数的。

Floating point numbers are limited in their precision. 浮点数的精度受到限制。 For really precise numbers you should use double instead. 对于真正精确的数字,您应该改用double

See also this answer: why-is-floating-point-arithmetic-in-c-sharp-imprecise? 另请参阅以下答案: 为什么C尖锐的浮点运算不精确? and have a look at this for more information: What Every Computer Scientist Should Know About Floating-Point Arithmetic 并查看以下内容以获取更多信息: 每位计算机科学家都应了解的浮点算法

var tmp = "263148,21";
var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.NumberFormat.NumberDecimalSeparator = ",";
var ftmp = double.Parse(tmp, culture);

You have to use double instead of float 您必须使用double而不是float

As stated in other answers and comments, this is related to floating point precision. 如其他答案和评论所述,这与浮点精度有关。

Consider using Decimal if you need to have the exact same decimals or to leverage rounding errors. 如果您需要使用完全相同的小数位数或利用舍入误差,请考虑使用十进制 But please note that this type is much more heavy weight (128 bits) and might not be suited for your case. 但是请注意,这种类型的重量更重(128位),可能不适合您的情况。

var tmp = "263148,21";
var dtmp = Decimal.Parse(tmp); //263148.21

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM