Rounding a double to 5 decimal places in Java ME

前端 未结 8 466
旧时难觅i
旧时难觅i 2020-12-10 05:18

How do I round a double to 5 decimal places, without using DecimalFormat?

相关标签:
8条回答
  • 2020-12-10 06:06

    You can round to the fifth decimal place by making it the first decimal place by multiplying your number. Then do normal rounding, and make it the fifth decimal place again.

    Let's say the value to round is a double named x:

    double factor = 1e5; // = 1 * 10^5 = 100000.
    double result = Math.round(x * factor) / factor;
    

    If you want to round to 6 decimal places, let factor be 1e6, and so on.

    0 讨论(0)
  • 2020-12-10 06:08

    Multiply by 100000. Add 0.5. Truncate to integer. Then divide by 100000.

    Code:

    double original = 17.77777777;
    int factor = 100000;
    int scaled_and_rounded = (int)(original * factor + 0.5);
    double rounded = (double)scaled_and_rounded / factor;
    
    0 讨论(0)
提交回复
热议问题