C#浮precision

问题描述:

任何人能请向我解释这里发生了什么:

Can anyone please explain to me what's happening here:

using System;
using System.Text;

namespace ConsoleApplication1 {

    class Program {

        static void Main(string[] args) {

            object o = 1000000.123f;
            float f= Convert.ToSingle(o);
            double d = Convert.ToDouble(f);

            Console.WriteLine(f.ToString("r"));
            Console.WriteLine(d.ToString("r"));

            Console.ReadLine();

        }
    }
}

它输出:

1000000.13

1000000.13

1000000.125

1000000.125

我的预期:

对象O有一个基本的浮点类型(似乎发生[从观察的观察窗口,它的类型为对象{浮动})

The object o to have an underlying float type (seems to happen [from observing the watch window where it is typed as object {float})

这1000000.123f会被存储在F中为1000000.125(该IEEE754逼近32位?)

That 1000000.123f would get stored in f as 1000000.125 (The IEEE754 approximation in 32 bits?)

这双将存储1000000.125以及(似乎发生,即使˚F似乎不包含我所期待的)

That the double would store 1000000.125 as well (seems to happen even though f doesn't seem to contain what I expected)

这要求上的ToString往返格式会给我早在这两种情况下1000000.125。

That asking for a round trip format on the ToString would give me back 1000000.125 in both cases.

谁能告诉我,串起输出F时,我在做什么错了让1000000.13?

Can anyone tell me what I'm doing wrong to get 1000000.13 when stringing out f?

正如你已经看到,数1000000.123存储为1000000.125。这是呈现为-是 double.ToString(),但 float.ToString截断(),因为显示太多许多数字是误导性的。

As you have already observed, the number 1000000.123 is stored as 1000000.125. This is rendered as-is by double.ToString(), but truncated by float.ToString() because showing too many digits is misleading.

顺便说一句,有没有 Convert.ToSingle(浮点),因为它会简单地返回你传递什么。您的code其实解析为 Convert.ToSingle(双)。你是这样(隐式)转换为,然后(明确的)回浮动,这是一个无操作,是必须的。

Incidentally, there is no Convert.ToSingle(float) because it would simply return exactly what you passed in. Your code is actually resolving to Convert.ToSingle(double). You are thus (implicitly) converting to double and then (explicitly) back to float, which is a no-op, essentially.

注意:不要相信JavaScript的浮点计算器。他们中有些人断言,1000000.123由单precision花车,我猜是基于这样的,因为IEEE浮点数有大约7.22 precision数字,他们可以精确地重新$假设存储为1000000.1 p $ psented在8位。这是不正确。

Caution: Don't trust JavaScript floating point calculators. Some of them assert that 1000000.123 is stored as 1000000.1 by single-precision floats, which I'm guessing is based on the assumption that, because IEEE floats have roughly 7.22 digits of precision, they can be accurately represented in 8 digits. This is incorrect.