Here is my question :
If we have the following value
0.59144706948010461
and we try to convert it to Single we receive the next value:
0.591447055
As you can see this is not that we should receive. Could you please explain how does this value get created and how can I avoid this situation?
Thank you!
As you can see this is not that we should receive.
Why not? I strongly suspect that's the closest Single
value to the Double
you've given.
From the documentation for Single
, having fixed the typo:
All floating-point numbers have a limited number of significant digits, which also determines how accurately a floating-point value approximates a real number. A
Single
value has up to 7 decimal digits of precision, although a maximum of 9 digits is maintained internally.
Your Double
value is 0.5914471 when limited to 7 significant digits - and so is the Single
value you're getting. Your original Double
value isn't exactly 0.59144706948010461 either... the exact values of the Double
and Single
values are:
Double
: 0.5914470694801046146693579430575482547283172607421875Single
: 0.591447055339813232421875It's important that you understand a bit about how binary floating point works - see my articles on binary floating point and decimal floating point for more background.
See more on this question at Stackoverflow