使用ToString(“F1”)时不正确的浮点四舍五入 [英] Incorrect rounding of float when using ToString("F1")

查看:1735
本文介绍了使用ToString(“F1”)时不正确的浮点四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个浮点值:12345.6489

当我使用下面的格式:
$ b

(12345.6489f) .ToString(F1)



然后我得到结果

12345.7



但是这是不正确的,因为它应该是12345.6。

有谁知道为什么会出现这种情况?另一个提示是,在格式化之前强制转换返回正确的结果,如果我的浮点值比较小,例如1234.6489,那么我也得到了正确的结果。

解决方案

这似乎与前一个问题有关: .NET的Double.ToString方法



请注意,如果您调用 .ToString(G)在你的号码上,正确的四舍五入到 12345.65 。如果你四舍五入的数字,到一位小数,问题发生。

当我调查我自己的问题时,我也发现了一些例子,不能解释为所以请检查该线程。



添加:请注意,任何可以用 float ,也可以用 double 来表示(大量的零位)。可以使用下面的技巧(这个问题也提到了):

$ $ $ $ $ $ $ $ $> float x = 12345.6489f;
string trick =((double)x).ToString(F1);


I have a float value: 12345.6489

When I format this using:

(12345.6489f).ToString("F1")

Then I get a result of

12345.7

But this is incorrect, since it should be 12345.6.

Does anyone understand why this might occur? Another hint is that casting to double before I format returns the correct result, and if my float value is a little smaller, for example 1234.6489, then too I get the correct result.

解决方案

This seems to be related to a question I asked some time ago: Round-twice error in .NET's Double.ToString method

Note that if you call .ToString("G") on your number, it is correctly rounded to 12345.65. If you round the rounded number, to one decimal, the problem occurs.

When I investigated my own question earlier, I also found some examples that couldn't be explained as round-twice errors, so check that thread as well.

Addition: Note that any number that can be represented (exactly) by a float, can also be represented (with a lot of zero bits) by a double. One can use the following trick (which the question also mentions):

float x = 12345.6489f;
string trick = ((double)x).ToString("F1");

这篇关于使用ToString(“F1”)时不正确的浮点四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆