Reputation: 139
I would like to known is there a way to conver float like this 0,00749052940542251 to double without lossing precision and convert back into same float?
Upvotes: 2
Views: 223
Reputation: 154188
"0,00749052940542251" is not a float - exactly.
A 32-bit float can encode about 232 different values exactly. 0,00749052940542251 is not one of them. Instead when code assigns 0,00749052940542251 to a float, the float stores a nearby value:
0,007490529 213... The closest float
0,007490529 40542251
0,007490529 678... The next closest float
As double's precision and range exceeds float, any float --> double --> float can round-trip exactly.
0,00749052940542251 is not one of the about 264 different values encodable as a double either. Again, a nearby value is used. Closer, yet not the same.
0,007490529 4054225 099..
0,007490529 4054225 1
0,007490529 4054225 107..
Upvotes: 1
Reputation: 1171
Converting from float to double does not involve a loss of precision, as double is a higher-precision type than float.
However, your example number is too precise for the float type - storing that number in a float will always involve a loss of precision, because your number has 15 significant digits, and a float can only store 6 to 9 significant digits. A double can store 15 to 16. To understand better why this is, I've included some articles below from wikipedia. You may want to read more on floating-point numbers, which C#'s float and double types both are.
Further reading:
Wikipedia - Single (C# float)
Wikipedia - Double
Wikipedia - Floating-point Arithemtic
Upvotes: 3