Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best/fastest way to recognize if a string number is exactly representable in floating point (or double)?

Tags:

javascript

I'm trying to determine whether a given string that represents a decimal number is exactly representable as a double. I'd be particularly keen on a javascript solution, but anything is fine (I can port).

I could parseFloat, stringify, then see if that string matches the input string, but I'm wondering if there's a better/faster way to do this. I imagine someone with in depth knowledge of the IEEE floating point standards would have a better way to do this, but that person isn't me.

like image 528
B T Avatar asked Sep 29 '17 23:09

B T


1 Answers

Any number which has a fractional part that does not end with 5 is not exactly representable as a binary floating point number.

A representable number has a fractional part which is a sum of 1/(2^N). Any such sum ends with the digit 5.

This does not mean a number with 5 in the end is always representable, to refine this we would have to check if the fractional part is indeed such a sum.

like image 190
alain Avatar answered Nov 12 '22 08:11

alain