0

I am doing following in java- 1- Multiplying a floating point with 10 till the time its fractional part become zero. 2- tested this with

number%1 == 0 // fails here

Prob I am facing- e.g input value is .12 iter-1 .12*10 = 1.199999 iter-2 .12*100 = 12.010** // were expecting fraction as zero here

Expected- 
iter-1 .12*10 = 1.2
iter-2 .12*100 = 12.0

What are the ways I can get the same as expected.

Geek
  • 23
  • 4
  • 2
    You might want to do a little more reading on how floating point numbers are stored and managed. They are approximations and this sort of problem is pretty common if you think they do math like humans do it. You'd be better off counting the digits in the decimal portion and multiplying by that magnitude (and convert to int/long as appropriate). – WPrecht May 13 '16 at 18:29
  • Ultimately, the easiest way to do this is probably bit shifting or some sort of direct bit manipulation. You should refer to the IEEE FP standard for the bit layout. https://en.wikipedia.org/wiki/Single-precision_floating-point_format – Christopher Schneider May 13 '16 at 18:33
  • Possible dupe of http://stackoverflow.com/questions/588004/is-floating-point-math-broken – Louis Wasserman May 13 '16 at 20:55

2 Answers2

0

You can use Math.IEEEremainder(value, 1) == 0. But please make sure you want exact bit-aware check, rather than approximate check (like to only 10 digits or so) to avoid reporting non-round numbers of things like 1.00000000000001

Artur Biesiadowski
  • 3,595
  • 2
  • 13
  • 18
-2

How about

Double number = ...; // Some number
boolean hasFractionalPartInIt = number.compareTo((double)number.intValue()) != 0;