This question already has an answer here:
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.
Well, you can use:
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.Use modulo:
Another way to get the fraction without using Math is to cast to a long.
When you print a
double
the toString will perform a small amount of rounding so you don't see any rounding error. However, when you remove the integer part, the rounding is no longer enough and the rounding error becomes obvious.The way around this is to do the rounding yourself or use BigDecimal which allows you to control the rounding.
prints