tifi90
tifi90

Reputation: 413

String.format() rounding a double with leading zeros in digits - Java

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.

Upvotes: 7

Views: 2393

Answers (1)

Unmitigated
Unmitigated

Reputation: 89264

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.

Upvotes: 13

Related Questions