Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# NumberFormat.format()

Max Campa
Greenhorn
Posts: 10
Hi there,

I stepped trough the following code:

When reaching line 13 the format(double d) method returns the String "987.12346" instead of "987.12345"?

Regards,

Max

Max Campa
Greenhorn
Posts: 10
Why is the format(double d) method returning "987.12346" with the digit 6 instead of 5?

Thanks,

Max

Zandis Murāns
Ranch Hand
Posts: 174
Because last (fifth) number is rounded up. If 5 was followed by digits 0 to 4, result would be 987.12345.

Max Campa
Greenhorn
Posts: 10
Thanks Zandis,

where is this rule stated? Does this rule applies to float types too?

So if the double had been 987.123459 the output would be 987.12349.
If the double had been 987.123451 the output would be 987.12345.

I found this document on the Wikipedia about rounding floating point but I dont understand it http://en.wikipedia.org/wiki/Rounding#Types_of_roundings.

Thanks,

Max

Jesper de Jong
Java Cowboy
Sheriff
Posts: 16007
87
Besides the rounding problem, note that you should not expect a float or double to be able to hold numbers of arbitrary precision. A float has about 6 decimal digits of precision, and a double about 15 digits. Floats and doubles are stored as binary fractions and they can't represent some decimal numbers to exact precision; for example the number 0.1 cannot be stored in a float or double exactly. Some calculations will inevitably lead to rounding errors.

The API documentation of DecimalFormat says:
DecimalFormat provides rounding modes defined in RoundingMode for formatting. By default, it uses RoundingMode.HALF_EVEN.

Max Campa
Greenhorn
Posts: 10
Thanks Jesper.

Rob Poulos
Ranch Hand
Posts: 49
i think if you require strict floating-point numbers you would need to specify strictfp in either the method or class declaration. wouldnt this give you the exact number? or would you need BigDecimal involved?

dont mind me, i'm new

Max Campa
Greenhorn
Posts: 10
Hi Rob,

I just posted the code to understand the rules of rounding double primitive types.

You would probably use BigDecimal.

Max Campa
Greenhorn
Posts: 10
Ok so the rules are 0 to 4 rounds down and 5 to 9 rounds up for example:

This would result to 987.12346.

If I use a float primitive type:

This would result to 987.12347.

Why do we get 7 instead of 6. Where do I find these rules in the Java documentation?

Thanks