Java Double Round up to 2 decimal places always

I am trying to round double values ​​to two decimal digits, however it does not work 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, regardless of whether a decimal fraction exists or not, always keep the values ​​up to two decimal places, even if you need to add extra zeros.

Any help is appreciated!

+6
source share
4 answers

There are two things that can be improved in the code.

First, casting a double to BigDecimal to round it is very inefficient. Instead, you should use Math.round:

  double value = 1.125879D; double valueRounded = Math.round(value * 100D) / 100D; 

Secondly, when printing or converting a real number into a string, you can use System.out.printf or String.format. In your case, using the format "% .2f" does the trick.

  System.out.printf("%.2f", valueRounded); 
+11
source

I am using the format () function of the String class. Much easier. 2 in "% .2f" indicates the number of digits after the decimal point you want to display. A value of f in "% .2f" means that you are printing a floating point number. Here is the string formatting documentation ( http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax )

 double number = 12.34567; System.out.println(String.format("%.2f", number)); 
+4
source

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)); } 
+3
source

You convert BigDecimal back to double , which essentially trims 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(); } 
+2
source

Source: https://habr.com/ru/post/975674/


All Articles