Using Math.round to round to one decimal place?

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

    If you need this and similar operations more often, it may be more convenient to find the right library instead of implementing it yourself.

    Here are one-liners solving your question from Apache Commons Math using Precision, Colt using Functions, and Weka using Utils:

    double value = 540.512 / 1978.8 * 100;
    // Apache commons math
    double rounded1 = Precision.round(value, 1);
    double rounded2 = Precision.round(value, 1, BigDecimal.ROUND_HALF_UP);
    // Colt
    double rounded3 = Functions.round(0.1).apply(value)
    // Weka
    double rounded4 = Utils.roundDouble(value, 1)
    

    Maven dependencies:

    
        org.apache.commons
        commons-math3
        3.5
    
    
    
        colt
        colt
        1.2.0
    
    
    
        nz.ac.waikato.cms.weka
        weka-stable
        3.6.12
    
    

提交回复
热议问题