Using Math.round to round to one decimal place?

前端 未结 9 1241
别跟我提以往
别跟我提以往 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
    
    0 讨论(0)
  • 2020-12-05 10:05
    Double toBeTruncated = new Double("2.25");
    
    Double truncatedDouble = new BigDecimal(toBeTruncated).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
    

    it will return 2.3

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

    try this

    for example

    DecimalFormat df = new DecimalFormat("#.##");
    df.format(55.544545);
    

    output:

    55.54
    
    0 讨论(0)
  • 2020-12-05 10:09
    DecimalFormat decimalFormat = new DecimalFormat(".#");
    String result = decimalFormat.format(12.763);                // -->  12.7
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 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:

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-math3</artifactId>
        <version>3.5</version>
    </dependency>
    
    <dependency>
        <groupId>colt</groupId>
        <artifactId>colt</artifactId>
        <version>1.2.0</version>
    </dependency>
    
    <dependency>
        <groupId>nz.ac.waikato.cms.weka</groupId>
        <artifactId>weka-stable</artifactId>
        <version>3.6.12</version>
    </dependency>
    
    0 讨论(0)
提交回复
热议问题