I have a set of base-10 nonnegative floats with either three or four digits to the right of the decimal point. Can anyone suggest a reliable way to extract the very rightmost digit (that is, the 1E-4 place) without running into occasional floating-point issues?
My first attempt, lastDigit = round(10*rem(num*1000,1)), works most of the time:
>> num = 130404809.288; lastDigit = round(10*rem(num*1000,1)) % fourth digit right of the decimal point is zero
lastDigit = 0>> num = 130404809.2882; lastDigit = round(10*rem(num*1000,1))lastDigit = 2
But every once in a while, the finite nature of internal binary representation produces undesired results:
>> num = 136147309.434; lastDigit = round(10*rem(num*1000,1)) % should return zero
lastDigit = 10
I realize this is a common subtlety, and that my challenge is really not so much math as string parsing—but this is the data I have to work with.
Naively, I tried various combinations of floor, round, rem, etc. — but I haven't been able to find a clean way to extract that fourth digit that doesn't run into cases like the one above every so often. Can anyone set me straight?
Best Answer