The conversion can be handy though if you want to output short strings in decimal format though.
For instance when writing an optimizer for SVG path strings you might want to change absolute positions into relative positions and vice versa.
You could be at the absolute position 0.1 and want to add the relative position 0.2. With doubles you will end up at 0.30000000000000004, as 0.1 and 0.2 cannot be exactly represented in binary floating point.
If you parse as double and do all calculations in double precision your error will be less than the precision of single precision. If you convert to single just before formatting, the formatting routine will look for the shortest decimal number within the precision of single precision.
You usually end up with the same result as with lossless decimal math.
It’s important to remember that this trick relies on your binary floating point numbers just being storage for decimal floating point numbers with low precision.
The conversion can be handy though if you want to output short strings in decimal format though.
For instance when writing an optimizer for SVG path strings you might want to change absolute positions into relative positions and vice versa.
You could be at the absolute position 0.1 and want to add the relative position 0.2. With doubles you will end up at 0.30000000000000004, as 0.1 and 0.2 cannot be exactly represented in binary floating point.
If you parse as double and do all calculations in double precision your error will be less than the precision of single precision. If you convert to single just before formatting, the formatting routine will look for the shortest decimal number within the precision of single precision.
You usually end up with the same result as with lossless decimal math.
It’s important to remember that this trick relies on your binary floating point numbers just being storage for decimal floating point numbers with low precision.