Tyrick
Tyrick

Reputation: 2966

Formatting decimal places in Java

I'm trying to format a double to just 2 decimal places in Java.

I've read the following post: How to round a number to n decimal places in Java

For some reason, every one of those methods fails to work on certain numbers I have..

For example:

DecimalFormat df = new DecimalFormat("#.##");
normalizedValue = Double.valueOf(df.format(normalizedValue));

If I print normalizedValue I get result similar to the following:

-78.64000000000001

18.97

59.469999999999985

-63.120000000000005

(Note: some are formatted correctly... some aren't)

So, these methods seem to round, but I need something that will remove all decimals after 2 decimal places... Any suggestions?

Thank you.

Upvotes: 0

Views: 2170

Answers (1)

Howard
Howard

Reputation: 39197

The string representation given by DecimalFormat.format(...) does indeed have only 2 digits in your example. But as soon as you reconvert it into a double those accuracy issues occur. A binary base format like double will always show such effects when you try to represent "exakt" decimal fractions. You may change to BigDecimal to get rid of such effects.

Upvotes: 5

Related Questions