Using Math.round to round to one decimal place?

前端 未结 9 1247
别跟我提以往
别跟我提以往 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条回答
  •  -上瘾入骨i
    2020-12-05 10:13

    A neat alternative that is much more readable in my opinion, however, arguably a tad less efficient due to the conversions between double and String:

    double num = 540.512;
    double sum = 1978.8;
    
    // NOTE: This does take care of rounding
    String str = String.format("%.1f", (num/sum) * 100.0); 
    

    If you want the answer as a double, you could of course convert it back:

    double ans = Double.parseDouble(str);
    

提交回复
热议问题