I am trying to round off the double values to 2 decimal digits, however it's not working in all scenarios
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
public static void main(String[] args) {
System.out.println(round(25.0,2)); //25.0 - expected 25.00
System.out.println(round(25.00d,2)); //25.0 - expected 25.00
System.out.println(round(25,2)); //25.0 - expected 25.00
System.out.println(round(25.666,2)); //25.67
}
In short, no matter whether decimal exists or not, always hold the values upto 2 decimal even if it needs to pad additional zeros.
Any help is appreciated!
In your case using format "%. 2f" does the trick. "First" part is necessary only if you need to get rounded value as double. Formatting with precision does proper rounding as well, so if the end goal of your program is to get string representation of the rounded value, all you need is String.
Double can provide precision up to 15 to 16 decimal points.
There are two things that can be improved in your code.
First, casting double to BigDecimal in order to round it is very inefficient approach. You should use Math.round instead:
double value = 1.125879D;
double valueRounded = Math.round(value * 100D) / 100D;
Second, when you print or convert real number to string, you may consider using System.out.printf or String.format. In your case using format "%.2f" does the trick.
System.out.printf("%.2f", valueRounded);
I use the format() function of String class. Much simpler code. The 2 in "%.2f" indicates the number of digits after the decimal point you want to display. The f in "%.2f" indicates that you are printing a floating point number. Here is the documentation on formatting a string (http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax)
double number = 12.34567;
System.out.println(String.format("%.2f", number));
This will work for you:
public static void main(String[] args) {
DecimalFormat two = new DecimalFormat("0.00"); //Make new decimal format
System.out.println(two.format(25.0));
System.out.println(two.format(25.00d));
System.out.println(two.format(25));
System.out.println(two.format(25.666));
}
You are converting BigDecimal
back to double
which essentially trim the trailing zeros.
You can return either BigDecimal
or BigDecimal.toPlainString()
.
public static String round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.toPlainString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With