0

I cannot figure out why a float cannot hold the given value. It seems like it should be able to.

This C# code demonstrates the problem:

    float @val = 1571563892;
    @val.Dump();               // output: 1,571564E+09 (12 more)
    @val.ToString("F").Dump(); // output: 1571564000,00

this is the output: (12 more)

1,571564E+09
1571564000,00
Martin Lottering
  • 1,624
  • 19
  • 31
  • 2
    `float` in C# is IEEE-754 single precision which can only hold ~7 digits of precision and can't represent exactly values such as 1571563892 – phuclv Oct 31 '19 at 08:44
  • 1
    You can use double to hold this value. Prefer double (8 bytes) than float (4 bytes) when possible. Or [decimal](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/types#the-decimal-type) depending of the case. [Floating-point numeric types (C# reference)](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types). [Difference between decimal, float and double in .NET?](https://stackoverflow.com/questions/618535/difference-between-decimal-float-and-double-in-net) –  Oct 31 '19 at 08:46
  • 1
    [Exact representation of integers in floating points](https://stackoverflow.com/q/52086887/995714), [Are there any whole numbers which the double cannot represent within the MIN/MAX range of a double?](https://stackoverflow.com/q/19473352/995714) – phuclv Oct 31 '19 at 08:47
  • Thank you guys. Its still shocking. – Martin Lottering Oct 31 '19 at 08:54
  • It is because of the number of bytes used to store the value number part AND the exponent part. float and double are approximations: so float is less precise than double. When assigning a float or double, sometimes the CPU automatically lost precision in the mantissa. Hence GPU power. https://en.wikipedia.org/wiki/Floating-point_arithmetic and https://www.ntu.edu.sg/home/ehchua/programming/java/DataRepresentation.html –  Oct 31 '19 at 09:01

0 Answers0