Reputation: 79425
How to display 0.05 as 0.0, 0.05 and 0.050?
My code
double x = 0.05;
System.out.printf("%.1f%n", x);
System.out.printf("%.2f%n", x);
System.out.printf("%.3f%n", x);
prints
0.1
0.05
0.050
I want the first result as 0.0.
Louis Wasserman has suggested doing it using BigDecimal but I do not know how to use BigDecimal to do it.
Upvotes: 1
Views: 168
Reputation: 1367
Try the following examples:
double roundedTotal = new BigDecimal(0.05).setScale(1, RoundingMode.FLOOR).doubleValue();
roundedTotal ==> 0.0
roundedTotal = new BigDecimal(0.09).setScale(1, RoundingMode.FLOOR).doubleValue();
roundedTotal ==> 0.0
roundedTotal = new BigDecimal(0.59).setScale(1, RoundingMode.FLOOR).doubleValue();
roundedTotal ==> 0.5
roundedTotal = new BigDecimal(0.599).setScale(2, RoundingMode.FLOOR).doubleValue();
roundedTotal ==> 0.59
So in your case it should be like this:
double x = 0.05;
System.out.printf("%.1f%n", new BigDecimal(x).setScale(1, RoundingMode.FLOOR).doubleValue());
System.out.printf("%.2f%n", new BigDecimal(x).setScale(2, RoundingMode.FLOOR).doubleValue());
System.out.printf("%.3f%n", new BigDecimal(x).setScale(3, RoundingMode.FLOOR).doubleValue());
Upvotes: 2
Reputation: 14175
Alternatively to BigDecimal, you can also use DecimalFormat
which might be more appropriate for you purposes:
double number = 0.050;
DecimalFormat df1 = new DecimalFormat("#.#");
DecimalFormat df2 = new DecimalFormat("#.##");
DecimalFormat df3 = new DecimalFormat("#.###");
df1.setRoundingMode(RoundingMode.FLOOR);
df1.setMinimumFractionDigits(1);
df2.setMinimumFractionDigits(2);
df3.setMinimumFractionDigits(3);
System.out.println(df1.format(number));
System.out.println(df2.format(number));
System.out.println(df3.format(number));
Upvotes: 3