I am trying to store 49212.619 in float value and don't want to loose any precision.
But it always change to this. I have tried this with different floating point numbers having length of 5 or 6 digits after decimal and similar behaviour is seen.
So I was just wondering despite the Float range being so large from this ideally 3.7 * 10 raise to 37
why is it not able to store these values.
E.g.
let floatVal: Float = 49212.619
print(floatVal) -> 49212.617
Because the greater the magnitude of a floating point value, the greater the distance between the values (see the .ulp property of Float).
At the .binade of Float¨s highest (non-infinite) representable value, the distance between representable values is: Float.greatestFiniteMagnitude.ulp = 2.02824096E+31
: )
And even at such a relatively small magnitude as a million, the distance between each representable value is as large as: Float(1_000_000).ulp == 0.0625
Float has 24 bits of precision, which is approximately 7 decimal digits. Your number has 8 digits, so it is to be expected that when rounded to Float the last digit or 2 will be off.
For comparison, Double has 53 bits of precision, which is approximately 16 decimal digits.
Note that what matters is the total number of digits, not where the decimal point is. That’s why these are called “floating-point” numbers: the position of the decimal point is stored separately. (And of course it’s all stored in binary not decimal, which is why such rounding occurs in the first place.)
And, of course, it all depends on what you intend to do with it once you've stored it.
For example, if all you need is to store the value 49212.619, then it is exactly representable as eg the String value "49212.619". But you cannot do arithmetic etc with it.