1

I have a problem with conversation of double values. In the picture Project's framework is .NET6 and i tried on .NET5 and i get same value again on x64.

Can you explain this situation to me? And how can I get the value unchanged on x64?

Thank you.

  • 1
    Short: use `decimal`. https://stackoverflow.com/questions/1165761/decimal-vs-double-which-one-should-i-use-and-when – Tim Schmelter Oct 21 '22 at 07:03
  • Thank you @TimSchmelter, but I need to send this value to a service and the value type is double. – Ozan Kazanç Oct 21 '22 at 07:27
  • @OzanKazanç assuming "service" means web service, and that you're sending a JSON payload.. the C# decimal type will be serialized to a value the service will handle just fine. JSON doesn't differentiate between integer, decimal and floating point. I've seen lots of REST calls documented as taking a double value when they mean decimal. – Charles Oct 21 '22 at 14:30

1 Answers1

1

This is expected behavior: floating point numbers have a limited number of significant digits, and a number that has a finite number of digits in their decimal representation may require infinite digits in their binary representation.

E.g., the decimal 0.1 is, in binary, 0.00011001100110011.... repeating. Storing this in a float or double, the number of digits is truncated.

Floating point numbers behave similar, but not identical to "real" numbers. This is something you should be aware of.

For financial mathematics, in C#, use the decimal type.

Here you find a good "what every developer should know" overview: https://floating-point-gui.de/.

The standard governing the most common (almost ubiquitous) implementation of floating point types is IEEE 754.

peterchen
  • 40,917
  • 20
  • 104
  • 186