how-to

Math

How to round number to two decimal places

For rounding to decimal places use java.text.DecimalFormat.

double d = 4.56;

DecimalFormat f = new DecimalFormat( "#.##" );

System.out.println( Double.valueOf( f.format( d ) ) );

Output is:

4.56

For country, where is used char ',' as decimal separator, is the situation more complicated. My recomedation is to "trasfer" decimal separator to common char - in this case to '.' char.

Then use this code:

double d = 4.56;

DecimalFormat f = new DecimalFormat( "#.##" );

/* this section is needed when you national decimal symbol is not '.', but is ',' */

DecimalFormatSymbols s = f.getDecimalFormatSymbols();
s.setDecimalSeparator( '.' );
f.setDecimalFormatSymbols( s );

/* rounding */

System.out.println( Double.valueOf( f.format( d ) ) );

The output is same as in previous example.