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...
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.
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