The documentation for Double states…
As Double using IEEE floating point there are some values that cannot be represented as a Double. For example, consider this code:
Var d1 As Double = 5.1 Var d2 As Double = d1 * 100 Var d3 As Double = Round(d1 * 100)
The value 5.1 cannot be stored directly in a Double (it’s actually more like 5.0999999999999996). When you multiple that actually value by 100 you end up with 509.9999999999999432 (this is d2 ) when you are really expecting a value of 510. In this case you want to use the Round method to get the value you want (d3 ).
Ok, but what if I really needed to store 5.1?!
Specifically, I need to send it as part of a JSON body.
If I divide d3 by 100 to get my decimal precision back, I get the same thing as before
{
"d1": 5.0999999999999996447,
"d2": 509.99999999999994316,
"d3": 510.0,
"d4": 5.0999999999999996447
}
Even if I convert it to a string with a fixed decimal…
Var d1 As Double = 5.1
Var d2 As Double = d1 * 100
Var d3 As Double = Round(d1 * 100)
Var d4 As Double = d3 / 100
Var s4 As String = Format(d4, "#.00")
Var d5 As Double = s4.ToDouble
It still makes up extra numbers when I convert it back again.
{
"d1": 5.0999999999999996447,
"d2": 509.99999999999994316,
"d3": 510.0,
"d4": 5.0999999999999996447,
"s4": "5.10",
"d5": 5.0999999999999996447
}
What am I missing here? I have to send accurate decimal numbers to a REST API that then compares them with other numbers. Asking if my number is the same as their number always fails.