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??
format(“%. 2f”) We also can use String formater %2f to round the double 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With