Does casting double to float always return same value?

后端 未结 6 1989
余生分开走
余生分开走 2020-12-17 09:10

Does casting double to float always produce same result, or can there be some \"rounding differences\"?

For example, is x in

6条回答
  •  清酒与你
    2020-12-17 09:43

    Floating-point numbers in C# are stored using the IEEE 754 format (http://en.wikipedia.org/wiki/IEEE_754). This format has two parts: the digits and the exponent. Doubles hold 52 digits, and floats hold 23 digits. The base is 2, not ten. So for your example above (0.123456789), the digits would be 111010110111100110100010101 (the binary representation of 123456789). That's 27 digits, which fits comfortably in a double, but not in a float, so yes, precision would be lost in the round-trip conversion.

    On the other hand, if your number was 0.123456, the digits would be 11110001001000000 (17 digits) which fits comfortably in either a float or a decimal, so you would lose no precision in a round-trip cast.

提交回复
热议问题