Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DecimalFormat rounding

Tags:

Here is small code to illustrate what I am seeing

float floater = 59.999f;  DecimalFormat df = new DecimalFormat("00.0");  System.out.println(df.format(floater)); 

This prints:

60.0 

I would like it to print

59.9 

What do I need to do?

like image 455
mainstringargs Avatar asked Jun 22 '11 22:06

mainstringargs


People also ask

What is DecimalFormat?

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits.

What is the default rounding mode?

The default rounding mode of DecimalFormat is RoundingMode. HALF_EVEN . This means that it rounds up, or rounds down if the number is nearer to the next neighbour. When the number is exactly between two neighbours (in your case, 2 and 3), it rounds to the nearest even number (in your case, 2).

How do you round to 2 decimal places in Java?

DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number always round to 2 decimal places.


1 Answers

Add this line before using the DecimalFormat:

df.setRoundingMode(RoundingMode.DOWN); 

Take a look at the other rounding modes and see which one is best for you.

Note : this method works only in JDK 1.6 or above

like image 102
Michael Borgwardt Avatar answered Nov 11 '22 23:11

Michael Borgwardt