How to get the numbers after the decimal point? (java)

David picture David · May 29, 2011 · Viewed 85.1k times · Source
 double d = 4.321562;

Is there an easy way to extract the 0.321562 on it's own from d? I tried looking in the math class but no luck. If this can be done without converting to string or casting to anything else, even better.

Answer

Jon Skeet picture Jon Skeet · May 29, 2011

Well, you can use:

double x = d - Math.floor(d);

Note that due to the way that binary floating point works, that won't give you exactly 0.321562, as the original value isn't exactly 4.321562. If you're really interested in exact digits, you should use BigDecimal instead.