简体   繁体   English

C#字符串浮动

[英]C# String to Float

When I convert a string to a float I get my answer plus a bunch of junk decimals. 当我将字符串转换为浮点数时,我得到了答案以及一堆垃圾小数。 How do I fix this? 我该如何解决? Is this floats error I'm seeing? 这是我看到的浮动错误吗?

string myFloat = "1.94";
float f = float.Parse(myFloat);

It needs to be a float for database reasons ... 由于数据库原因,它必须是float。

By junk I mean 1.94 turns into: 1.94000005722046 垃圾,我的意思是1.94变成:1.94000005722046

The problem is that you can't use float / double if you want a precise representation of your parsed number. 问题是,如果要精确表示已解析的数字,则不能使用float / double。 In case you need that you must use decimal . 万一您需要使用decimal For money amounts its almost always required to use decimal . 对于金钱,几乎总是需要使用decimal So keep that in mind. 所以记住这一点。

Please read about how floating point numbers are represented internally: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html 请阅读有关内部如何表示浮点数的信息: http : //docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

How 1.94 is represented internally by a float can be tested in this calculator: http://pages.cs.wisc.edu/~rkennedy/exact-float?number=1.94 可以在此计算器中测试如何用浮点数内部表示1.94: http//pages.cs.wisc.edu/~rkennedy/exact-float ?number = 1.94

As you see its 1.940000057220458984375 . 如您所见1.940000057220458984375


Databases support the decimal datatype: 数据库支持decimal数据类型:

You can change it to a double to get a more accurate representation but if you need it exactly You cannot fix this this is how floats are represented in computers. 您可以将其更改为双精度以得到更准确的表示形式,但是如果确实需要它,则无法解决,这就是浮点数在计算机中的表示方式。 If you use the decimal data type you will get an exact representation. 如果使用十进制数据类型,则将获得精确的表示形式。

string myFloat = "1.94";
decimal f = decimal.Parse(myFloat);

And then do the conversion to double when you store it to the database. 然后,将其存储到数据库时,将其转换为两倍。 You could still get some noise in the database. 您仍然可能在数据库中听到一些噪音。 The only way to be sure to get rid of this is to use numeric in the database. 确保摆脱这种情况的唯一方法是在数据库中使用数字。

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

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