Reputation: 4435
I need to print doubles rounded to a variable number of digits after decimal point so that insignificant zeros are not printed. E.g. I want both numbers 123 and 123.4 to be printed as is -- the first one without decimal point and the second one with it. If there are more than significant digits after decimal point then the number should be truncated to six digits.
What I describe is the default behavior of boost::locale::format if you print numbers as boost::locale::format("{1,number}") % double_value
. What I need is to do the same in Java, desirably using String.format. I tried %f
and %g
, but both of them print at least six digits.
All numbers I want to format are in range [0.1, 30000] so turning to scientific form should not be a pain here.
Upvotes: 5
Views: 3829
Reputation: 12932
There are various methods to format floating point numbers in Java.
First, format string allow you to specify a precision. The following code
System.out.printf("%.2f - %.2f", 123, 123.4)
will display 123.00 - 123.40
. Note that this is not exactly what you asked for, because the displayed numbers always have two fractional digits.
For more control over the format of the numbers, you can use the DecimalFormat
class. The following code has the behaviour you describe:
DecimalFormat form = new DecimalFormat("#.##");
form.setRoundingMode(RoundingMode.HALF_UP);
System.out.printf("%s - %s", form.format(123), form.format(123.4));
outputs: 123 - 123.4
.
Upvotes: 2
Reputation: 4435
Use DecimalFormat as explained here.
DecimalFormat df = new DecimalFormat("#0.######");
df.format(0.912385);
Upvotes: 6