Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - When two floating-point numbers are divided in java, they should be integers but become decimals.
When two floating-point numbers are divided in java, they should be integers but become decimals.
Mainly because simple types in java are not suitable for accurate calculation of floating points. Other languages have the same problem.

Computers store numerical values, which are binary. ? When processing, the floating-point number (double) is also converted into integer and then into binary, and then the operation is performed. If there is a remainder, there will be different ways of remainder. Plus, after the operation is completed, more binary will be converted to floating point, and there will be some trade-offs. It caused a simple and obvious error when it was submitted.

You can try the following code:

System.out.println(0.05? +? 0.0 1); //? 0.060000000000000005

System.out.println( 1.0? -? 0.42); ? //? 0.580000000000000 1

System.out.println(4.0 15? *? 100); //? 40 1.49999999999994

System.out.println( 123.3? /? 100); ? //? 1.239999 When accurate calculation is required,? Math.round()? Or? Decimal format ("0.00"). Format (4.025)) is not desirable.

Use BigDecimal or BCD code.

Use? When using BigDecimal, do you want to use it? New? BigDecimal (string ss) is a constructor.

The constructor public BigDecimal(double val) is also not recommended. You can refer to the comments of this function.

BigDecimal B2 = new BigDecimal(" 0.3 ");

BigDecimal b 1 = new BigDecimal(" 1.8 ");

system . out . println(b 1 . divide(B2));