简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM