Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to Format a Double value to 2 Decimal places [duplicate]

Tags:

java

I am dealing with lot of double values in my application, is there is any easy way to handle the formatting of decimal values in Java?

Is there any other better way of doing it than

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

What i want to do basically is format double values like

23.59004  to 23.59  35.7  to 35.70  3.0 to 3.00  9 to 9.00 
like image 633
Rajesh Pantula Avatar asked Jan 11 '12 13:01

Rajesh Pantula


People also ask

What is the number 2.738 correct to 2 decimal places?

What is 2.738 Round to Two Decimal Places? In the given number 2.738, the digit at the thousandths place is 8, so we will add 1 to the hundredths place digit. So, 3+1=4. Therefore, the value of 2.738 round to two decimal places is 2.74.

How do you format a double value?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places. /* Code example to print a double to two decimal places with Java printf */ System.


1 Answers

No, there is no better way.

Actually you have an error in your pattern. What you want is:

DecimalFormat df = new DecimalFormat("#.00");  

Note the "00", meaning exactly two decimal places.

If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".

like image 55
Bohemian Avatar answered Oct 15 '22 10:10

Bohemian