Double decimal formatting in Java
I'm having some problems formatting the decimals of a double. If I have a double value, e.g. 4.0, how do I format the decimals so that it's 4.00 instead?
One of the way would be using NumberFormat.
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(4.0));
Output:
4.00
With Java 8, you can use format
method..: -
System.out.format("%.2f", 4.0); // OR
System.out.printf("%.2f", 4.0);
-
f
is used forfloating
point value.. -
2
after decimal denotes, number of decimal places after.
For most Java versions, you can use DecimalFormat
: -
DecimalFormat formatter = new DecimalFormat("#0.00");
double d = 4.0;
System.out.println(formatter.format(d));
Use String.format:
String.format("%.2f", 4.52135);
As per docs:
The locale always used is the one returned by
Locale.getDefault()
.
Using String.format, you can do this:
double price = 52000;
String.format("$%,.2f", price);
Notice the comma which makes this different from @Vincent's answer
Output:
$52,000.00
A good resource for formatting is the official java page on the subject