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

前端 未结 5 990
礼貌的吻别
礼貌的吻别 2021-02-14 00:28

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

private static double[] method(double d)
{
    int integerPart = 0;
    double fractionPart =         


        
5条回答
  •  忘掉有多难
    2021-02-14 00:33

    To see what is going on, take a look at the binary representations of the numbers:

    double d = 5.6;
    System.err.printf("%016x%n", Double.doubleToLongBits(d));
    double[] parts = method(d);
    System.err.printf("%016x %016x%n",
                      Double.doubleToLongBits(parts[0]),
                      Double.doubleToLongBits(parts[1]));
    

    output:

    4016666666666666
    4014000000000000 3fe3333333333330
    

    5.6 is 1.4 * 22, but 0.6 is 1.2 * 2-1. Because it has a lower exponent, normalization causes the mantissa to be shifted three bits to the left. The fact that the recurring terms (..66666..) were originally an approximation of the fraction 7/5 has been forgotten, and the missing bits are replaced with zeros.

    Given the original double value as input to your method, there is no way to avoid this. To preserve the exact value you would need to use a format that represents the desired value exactly, e.g. Fraction from Apache commons-math. (For this specific example with d=5.6 a BigDecimal would also be able to represent it exactly, but there are other numbers it cannot represent exactly, e.g. 4/3)

提交回复
热议问题