Using Math.round to round to one decimal place?

前端 未结 9 1242
别跟我提以往
别跟我提以往 2020-12-05 09:39

I have these two variables

double num = 540.512
double sum = 1978.8

Then I did this expression

double total = Math.round((         


        
相关标签:
9条回答
  • 2020-12-05 10:15
    Double number = new Double("5.25");
    Double tDouble = 
      new BigDecimal(number).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
    

    this will return it will return 5.3

    0 讨论(0)
  • 2020-12-05 10:17

    Helpful method I created a while ago...

    private static double round (double value, int precision) {
        int scale = (int) Math.pow(10, precision);
        return (double) Math.round(value * scale) / scale;
    }
    
    0 讨论(0)
  • 2020-12-05 10:26

    Your method is right, all you have to do is add a .0 after both the tens and it will fix your problem!

    double example = Math.round((187/35) * 10.0) / 10.0;
    

    The output would be:

    5.3
    
    0 讨论(0)
提交回复
热议问题