Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format double to 2 decimal places with leading 0s [duplicate]

Tags:

java

double

Possible Duplicate:
Round a double to 2 significant figures after decimal point

I am trying to format a double to 2 decimal places with leading zeros and there's no luck. Here is my code:

Double price = 32.0; DecimalFormat decim = new DecimalFormat("#.##"); Double price2 = Double.parseDouble(decim.format(price)); 

And I want output to be 32.00 instead I get 32.0
Any solutions??

like image 626
Bat_Programmer Avatar asked Oct 19 '10 23:10

Bat_Programmer


People also ask

How do you make a double show with two decimal places?

format(“%. 2f”) We also can use String formater %2f to round the double to 2 decimal places.

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 I keep last 0s after decimal point for double data type in Java?

To be able to print any given number with two zeros after the decimal point, we'll use one more time DecimalFormat class with a predefined pattern: public static double withTwoDecimalPlaces(double value) { DecimalFormat df = new DecimalFormat("#. 00"); return new Double(df.


1 Answers

OP wants leading zeroes. If that's the case, then as per Tofubeer:

    DecimalFormat decim = new DecimalFormat("0.00"); 

Edit:

Remember, we're talking about formatting numbers here, not the internal representation of the numbers.

    Double price = 32.0;     DecimalFormat decim = new DecimalFormat("0.00");     Double price2 = Double.parseDouble(decim.format(price));     System.out.println(price2); 

will print price2 using the default format. If you want to print the formatted representation, print using the format:

    String s = decim.format(price);     System.out.println("s is '"+s+"'"); 

In this light, I don't think your parseDouble() is doing what you want, nor can it.

like image 69
Tony Ennis Avatar answered Oct 08 '22 20:10

Tony Ennis