开发者

How do I round a double to two decimal places in Java? [duplicate]

This question already has answers here: How to round a number to n decimal places in Java 开发者_开发问答 (39 answers) Closed 3 years ago.

This is what I did to round a double to 2 decimal places:

amount = roundTwoDecimals(amount);

public double roundTwoDecimals(double d) {
    DecimalFormat twoDForm = new DecimalFormat("#.##");
    return Double.valueOf(twoDForm.format(d));
}

This works great if the amount = 25.3569 or something like that, but if the amount = 25.00 or the amount = 25.0, then I get 25.0! What I want is both rounding as well as formatting to 2 decimal places.


Just use: (easy as pie)

double number = 651.5176515121351;

number = Math.round(number * 100);
number = number/100;

The output will be 651.52


Are you working with money? Creating a String and then converting it back is pretty loopy.

Use BigDecimal. This has been discussed quite extensively. You should have a Money class and the amount should be a BigDecimal.

Even if you're not working with money, consider BigDecimal.


Use a digit place holder (0), as with '#' trailing/leading zeros show as absent:

DecimalFormat twoDForm = new DecimalFormat("#.00");


Use this

String.format("%.2f", doubleValue) // change 2, according to your requirement.


You can't 'round a double to [any number of] decimal places', because doubles don't have decimal places. You can convert a double to a base-10 String with N decimal places, because base-10 does have decimal places, but when you convert it back you are back in double-land, with binary fractional places.


This is the simplest i could make it but it gets the job done a lot easier than most examples ive seen.

    double total = 1.4563;

    total = Math.round(total * 100);

    System.out.println(total / 100);

The result is 1.46.


You can use org.apache.commons.math.util.MathUtils from apache common

double round = MathUtils.round(double1, 2, BigDecimal.ROUND_HALF_DOWN);


double amount = 25.00;

NumberFormat formatter = new DecimalFormat("#0.00");

System.out.println(formatter.format(amount));


You can use Apache Commons Math:

Precision.round(double x, int scale)

source: http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html#round(double,%20int)


Your Money class could be represented as a subclass of Long or having a member representing the money value as a native long. Then when assigning values to your money instantiations, you will always be storing values that are actually REAL money values. You simply output your Money object (via your Money's overridden toString() method) with the appropriate formatting. e.g $1.25 in a Money object's internal representation is 125. You represent the money as cents, or pence or whatever the minimum denomination in the currency you are sealing with is ... then format it on output. No you can NEVER store an 'illegal' money value, like say $1.257.


Starting java 1.8 you can do more with lambda expressions & checks for null. Also, one below can handle Float or Double & variable number of decimal points (including 2 :-)).

public static Double round(Number src, int decimalPlaces) {

    return Optional.ofNullable(src)
            .map(Number::doubleValue)
            .map(BigDecimal::new)
            .map(dbl -> dbl.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP))
            .map(BigDecimal::doubleValue)
            .orElse(null);
}


You can try this one:

public static String getRoundedValue(Double value, String format) {
    DecimalFormat df;
    if(format == null)
        df = new DecimalFormat("#.00");
    else 
        df = new DecimalFormat(format);
    return df.format(value);
}

or

public static double roundDoubleValue(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    long factor = (long) Math.pow(10, places);
    value = value * factor;
    long tmp = Math.round(value);
    return (double) tmp / factor;
}


DecimalFormat df = new DecimalFormat("###.##");
double total = Double.valueOf(val);


First declare a object of DecimalFormat class. Note the argument inside the DecimalFormat is #.00 which means exactly 2 decimal places of rounding off.

private static DecimalFormat df2 = new DecimalFormat("#.00");

Now, apply the format to your double value:

double input = 32.123456;
System.out.println("double : " + df2.format(input)); // Output: 32.12

Note in case of double input = 32.1;

Then the output would be 32.10 and so on.


If you want the result to two decimal places you can do

// assuming you want to round to Infinity.
double tip = (long) (amount * percent + 0.5) / 100.0; 

This result is not precise but Double.toString(double) will correct for this and print one to two decimal places. However as soon as you perform another calculation, you can get a result which will not be implicitly rounded. ;)


Math.round is one answer,

public class Util {
 public static Double formatDouble(Double valueToFormat) {
    long rounded = Math.round(valueToFormat*100);
    return rounded/100.0;
 }
}

Test in Spock,Groovy

void "test double format"(){
    given:
         Double performance = 0.6666666666666666
    when:
        Double formattedPerformance = Util.formatDouble(performance)
        println "######################## formatted ######################### => ${formattedPerformance}"
    then:
        0.67 == formattedPerformance

}


Presuming the amount could be positive as well as negative, rounding to two decimal places may use the following piece of code snippet.

amount = roundTwoDecimals(amount);

public double roundTwoDecimals(double d) {
    if (d < 0)
       d -= 0.005;
    else if (d > 0)
       d += 0.005;
    return (double)((long)(d * 100.0))/100);
}


where num is the double number

  • Integer 2 denotes the number of decimal places that we want to print.
  • Here we are taking 2 decimal palces

    System.out.printf("%.2f",num);


Here is an easy way that guarantee to output the myFixedNumber rounded to two decimal places:

import java.text.DecimalFormat;

public class TwoDecimalPlaces {
    static double myFixedNumber = 98765.4321;
    public static void main(String[] args) {

        System.out.println(new DecimalFormat("0.00").format(myFixedNumber));
    }
}

The result is: 98765.43


    int i = 180;
    int j = 1;
    double div=  ((double)(j*100)/i);
    DecimalFormat df = new DecimalFormat("#.00"); // simple way to format till any deciaml points
    System.out.println(div);
    System.out.println(df.format(div));


You can use this function.

import org.apache.commons.lang.StringUtils;
public static double roundToDecimals(double number, int c)
{
    String rightPad = StringUtils.rightPad("1", c+1, "0");
    int decimalPoint = Integer.parseInt(rightPad);
    number = Math.round(number * decimalPoint);
    return number/decimalPoint;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜