Search code examples
javamathnumbersdoubledecimal-point

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


 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.


Solution

  • 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.