Reputation: 6698
I'm currently using String.format("%.1f", number)
to format a double to have exactly 1 decimal number. However, they show up as 0.2
for instance. Is it possible to format it without the 0
so it looks like .2
?
When I search for this, all I can find are solutions on how to add more leading 0's...
Upvotes: 4
Views: 735
Reputation: 24802
You can use DecimalFormat
:
DecimalFormat formatter = new DecimalFormat("#.0"); // or the equivalent ".0"
System.out.println(formatter.format(0.564f)); // displays ".6"
System.out.println(formatter.format(12.546f)); // displays "12.5"
System.out.println(formatter.format(12f)); // displays "12.0"
In the format specifier, the use of #
over 0
indicates that no digit is to be displayed in case the value is absent.
If you don't want to display trailing zeroes you will want to use #.#
as the format specifier. The dot will not appear if there is no decimal part :
DecimalFormat formatter = new DecimalFormat("#.#");
System.out.println(formatter.format(0.564f)); // displays ".6"
System.out.println(formatter.format(12.546f)); // displays "12.5"
System.out.println(formatter.format(12f)); // displays "12"
Noticed how the 0.564
was rounded up? If that's not to your taste, you can change the rounding algorithm used by using the DecimalFormat.setRoundingMode(RoundingMode mode)
method. Use RoundingMode.DOWN
if you want to simply truncate the extra digits.
Upvotes: 6