7

I've asked this question already here in the comments:

How to round a number to n decimal places in Java.

I'm trying to convert a double into a string with a fixed number of decimal places. In the question above the solution is quite simple. When using

String.format("%.4g", 0.1234712)

I get the expected result, a number rounded to 4 digits:

0.1235

But when there are zeros after the decimal dot:

String.format("%.4g", 0.000987654321)

This will return:

0,0009877

It looks like the function is ignoring the leading zeros in the digits.

I know that I could just define a new DecimalFormat but I want to understand this issue. And learn a bit about the syntax.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
tifi90
  • 403
  • 4
  • 13

1 Answers1

12

Use %.4f to perform the rounding you want. This format specifier indicates a floating point value with 4 digits after the decimal place. Half-up rounding is used for this, meaning that if the last digit to be considered is greater than or equal to five, it will round up and any other cases will result in rounding down.

String.format("%.4f", 0.000987654321);

Demo

The %g format specifier is used to indicate how many significant digits in scientific notation are displayed. Leading zeroes are not significant, so they are skipped.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • 3
    Do you know by any chance how `%g` works? I've checked [Formatter Javadocs](https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html) but it's still unclear to me what it does. – Amongalen Jul 14 '20 at 06:33