Search code examples
javamathdoublefractions

What is the best way to separate double into two parts "integer & fraction" in java


I have tried to separate 5.6 (for example) by the following method:

private static double[] method(double d)
{
    int integerPart = 0;
    double fractionPart = 0.0;
    integerPart = (int) d;
    fractionPart = d - integerPart;
    return new double[]{integerPart, fractionPart};
}

But what I got is:

[0] = 5.0
[1] = 0.5999999999999996

Do you have any suggestion about doing this without converting the number to string?


Solution

  • Use BigDecimal to do that same calculation. (using doubles has precision problems because of its representation).

    • Construct it with new BigDecimal(String.valueOf(yourDouble)) (this is still going through string, but the parts are not separated via string manipulation)
    • use bd.subtract(new BigDecimal(bd.intValue()) to determine the fraction