4

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Ivan Smirnov
  • 4,036
  • 16
  • 29
  • 2
    That's not what "significant digits" is. Rounding to a certain number of decimal places is completely different from rounding to a certain number of significant digits. Rounding 1234567.891234 to 4 significant digits yields 1235000. Rounding 0.0000001234567 to 4 significant digits yields 0.0000001235. What you want to do (rounding to a number of decimal places is fine - its just not "significant digits". See http://www.purplemath.com/modules/rounding2.htm – hepcat72 Feb 06 '17 at 22:12

3 Answers3

5

Use DecimalFormat as explained here.

DecimalFormat df = new DecimalFormat("#0.######");
df.format(0.912385);
Community
  • 1
  • 1
Ivan Smirnov
  • 4,036
  • 16
  • 29
2

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.

Hoopje
  • 11,820
  • 6
  • 29
  • 47
-1

Use:

String.format("%.2f", floatValue);
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Mahender Yadav
  • 294
  • 1
  • 5