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

前端 未结 5 967
礼貌的吻别
礼貌的吻别 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:57

    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

提交回复
热议问题