简体   繁体   中英

Doing double - int in java

For example if I do this:

double decPart = 5.57 - 5;
System.out.println(decPart);

it returns 0.5700000000000003, instead of just 0.57. I can print it out properly using System.out.printf("%.2f", decPart), but that doesn't solve the problem (Note: the decimal part is not necessarily 2 decimal places). So for example if I try to do this:

System.out.println(1.0 - decPart);

it would return 0.4299999999999997

Can somebody please explain this behavior and how to fix it. Thanks in advance.

This is due to floating point imprecision . Floating-point numbers ( float , double in Java) cannot represent some numbers exactly. If you're looking for absolute precision, look into BigDecimal .

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