Using Math.round to round to one decimal place?

前端 未结 9 1250
别跟我提以往
别跟我提以往 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:01

    The Math.round method returns a long (or an int if you pass in a float), and Java's integer division is the culprit. Cast it back to a double, or use a double literal when dividing by 10. Either:

    double total = (double) Math.round((num / sum * 100) * 10) / 10;
    

    or

    double total = Math.round((num / sum * 100) * 10) / 10.0;
    

    Then you should get

    27.3
    

提交回复
热议问题