71

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.

james.garriss
  • 12,959
  • 7
  • 83
  • 96
sherry
  • 1,829
  • 7
  • 21
  • 23
  • this function sometimes return , instead of . on android, thus Double.valueOf() throws an exception – max4ever Feb 10 '12 at 12:34

21 Answers21

60

Just use: (easy as pie)

double number = 651.5176515121351;

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

The output will be 651.52

Kaspar
  • 617
  • 1
  • 5
  • 2
24

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.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Rob
  • 11,446
  • 7
  • 39
  • 57
  • Yes. I'm doing money. But all I'm doing is tip = (amount * percent)/100 and display tip and amount. I have considered BigDecimal but it seems like going through a lot of pain for such simple calculation. Isn't having a separate money class going overboard in this case? – sherry Apr 19 '11 at 04:53
  • 3
    Hell no. OO programming means classes are the answer to typing problems. Ask yourself the question: is Money a class of objects? Clearly the answer is yes. If that argument didn't sway you here are 2 more: 1. the Martin Fowler argument from Analysis Patterns: units need to be modeled or bad things happen, and 2. I have a money class I can give you if you like. – Rob Apr 21 '11 at 14:53
  • I'm not a pro with OOP but can you guys please tell me what should be the money class contain or do with the topic's situation. I can really figure it out. – newbie Apr 04 '14 at 01:50
  • Suggesting someone change a datatype as a solution probably doesn't apply to most working developers. – Jamie M. Dec 29 '16 at 18:01
  • Lots of inferences being made by Rob. Great analysis of the down-voter's problem! How about an analysis of the OP question? "I suppose it is tempting, if the only tool you have is a hammer, to treat everything as if it were a nail." _Maslow – Jamie M. Feb 21 '17 at 11:04
19

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

DecimalFormat twoDForm = new DecimalFormat("#.00");
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
11

Use this

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

Ajeet
  • 201
  • 3
  • 2
  • Dude you are genius! I've been trying to get this to work for a while. Your comment was it. lblTotal.setText( String.format("$%.2f",tip) ); – Joseph Kreifels II Jun 08 '16 at 14:39
8

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
6

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.

Austin
  • 61
  • 1
  • 1
3

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

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

xjodoin
  • 519
  • 5
  • 15
3

double amount = 25.00;

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

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

3

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)

Matias Elorriaga
  • 8,880
  • 5
  • 40
  • 58
2

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.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Dibyendu Mitra Roy
  • 1,604
  • 22
  • 20
1

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;
}
Flown
  • 11,480
  • 3
  • 45
  • 62
Maddy Sharma
  • 4,870
  • 2
  • 34
  • 40
1

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);
}
1
DecimalFormat df = new DecimalFormat("###.##");
double total = Double.valueOf(val);
Urvashi Gupta
  • 444
  • 4
  • 13
1

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.

0

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

}
prayagupa
  • 30,204
  • 14
  • 155
  • 192
  • with valueToFormat = 0d returns 0.0, not 0.00. Original question asked about two decimal places even in case of 0 value in decimals. – Atul Kumbhar Jun 07 '16 at 01:48
0

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);
}
Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69
0

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

selftaught91
  • 7,013
  • 3
  • 20
  • 26
0

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

S. Mayol
  • 2,565
  • 2
  • 27
  • 34
0
    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));
Ankit Gupta
  • 776
  • 5
  • 12
0

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

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

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