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

JavaDouble

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

Just use: (easy as pie)

double number = 651.5176515121351;

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

The output will be 651.52

Solution 2 - Java

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.

Solution 3 - Java

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

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

Solution 4 - Java

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.

Solution 5 - Java

Use this

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

Solution 6 - Java

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.

Solution 7 - Java

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

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

Solution 8 - Java

double amount = 25.00;

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

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

Solution 9 - Java

Solution 10 - Java

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.

Solution 11 - Java

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;
}

Solution 12 - Java

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);
}

Solution 13 - Java

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

Solution 14 - Java

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. ;)

Solution 15 - Java

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

}

Solution 16 - Java

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);
}

Solution 17 - Java

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);

Solution 18 - Java

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

Solution 19 - Java

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.

Solution 20 - Java

	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));

Solution 21 - Java

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;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsherryView Question on Stackoverflow
Solution 1 - JavaKasparView Answer on Stackoverflow
Solution 2 - JavaRobView Answer on Stackoverflow
Solution 3 - JavaMitch WheatView Answer on Stackoverflow
Solution 4 - Javauser207421View Answer on Stackoverflow
Solution 5 - JavaAjeetView Answer on Stackoverflow
Solution 6 - JavaAustinView Answer on Stackoverflow
Solution 7 - JavaxjodoinView Answer on Stackoverflow
Solution 8 - JavaZakila BanuView Answer on Stackoverflow
Solution 9 - JavaMatias ElorriagaView Answer on Stackoverflow
Solution 10 - JavaA.J. MayersView Answer on Stackoverflow
Solution 11 - JavaMaddyView Answer on Stackoverflow
Solution 12 - Javauser6078841View Answer on Stackoverflow
Solution 13 - JavaUrvashi GuptaView Answer on Stackoverflow
Solution 14 - JavaPeter LawreyView Answer on Stackoverflow
Solution 15 - JavaprayagupaView Answer on Stackoverflow
Solution 16 - JavaDr. Debasish JanaView Answer on Stackoverflow
Solution 17 - Javaselftaught91View Answer on Stackoverflow
Solution 18 - JavaS. MayolView Answer on Stackoverflow
Solution 19 - JavaDibyendu Mitra RoyView Answer on Stackoverflow
Solution 20 - JavaAnkit GuptaView Answer on Stackoverflow
Solution 21 - JavaRAJESH SAHAView Answer on Stackoverflow