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
There are many way you can do this. Those are given bellow:
Suppose your original number is given bellow:
double number = 2354548.235;
Using NumberFormat:
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(number));
Using String.format:
System.out.println(String.format("%,.2f", number));
Using DecimalFormat and pattern:
NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
DecimalFormat decimalFormatter = (DecimalFormat) nf;
decimalFormatter.applyPattern("#,###,###.##");
String fString = decimalFormatter.format(number);
System.out.println(fString);
Using DecimalFormat and pattern
DecimalFormat decimalFormat = new DecimalFormat("############.##");
BigDecimal formattedOutput = new BigDecimal(decimalFormat.format(number));
System.out.println(formattedOutput);
In all cases the output will be: 2354548.23
Note:
During rounding you can add RoundingMode
in your formatter. Here are some rounding mode given bellow:
decimalFormat.setRoundingMode(RoundingMode.CEILING);
decimalFormat.setRoundingMode(RoundingMode.FLOOR);
decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN);
decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
decimalFormat.setRoundingMode(RoundingMode.UP);
Here are the imports:
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
new DecimalFormat("#0.00").format(4.0d);
double d = 4.0;
DecimalFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
System.out.println(nf.format("#.##"));
Use String.format:
String.format("%.2f", 4.52135);
As per docs:
The locale always used is the one returned by
Locale.getDefault()
.
You could always use the static method printf from System.out
- you'd then implement the corresponding formatter; this saves heap space in which other examples required you to do.
Ex:
System.out.format("%.4f %n", 4.0);
System.out.printf("%.2f %n", 4.0);
Saves heap space which is a pretty big bonus, nonetheless I hold the opinion that this example is much more manageable than any other answer, especially since most programmers know the printf function from C (Java changes the function/method slightly though).