Float and double are designed for scientific calculations and engineering calculations and perform binary floating-point operations, which are designed to provide more accurate, fast approximation calculations over a wide range of numerical ranges. However, they do not provide completely accurate results, so they are not suitable for situations where precise results are required, especially in currency calculations.
// Suppose there are 1.03 yuan, after spending 0.42 yuan System.out.println (1.03-. 42); // 0.6100000000000001 System.out.println (1.00-9 *. 10); // 0.09999999999999998
Rounding solves the problem above, but not all problems can be solved with rounding, such as 1 yuan, 0.1,0.2,0.3, until 1 yuan of sweets, starting from 0.1 to buy, until it cannot be paid:
Public Static void Main (string[] args) { double funds = 1.00; int itemsbought = 0; for (double price =., funds >= price, price + =,) { -= Price ; Itemsbought++ ; } + "items bought." ); System.out.println ("money left over: $" + funds);}
The result is:
Using BigDecimal is the right approach:
Public Static voidMain (string[] args) {FinalBigDecimal ten_cents =NewBigDecimal (". 10"); intItemsbought = 0; BigDecimal Funds=NewBigDecimal ("1.00"); for(BigDecimal price = ten_cents; Funds.compareto (price) >= 0;Price.add (ten_cents)) {Itemsbought++; Funds=funds.subtract (price); } System.out.println (Itemsbought+ "items bought."); System.out.println ("Money left over: $" +funds);}
The result is:
The disadvantages of using BigDecimal are: 1. Inconvenient (need to create bigdecimal object) compared to basic type; 2. Slow
using int or long, depending on the size of the value involved, and processing the decimal decimals yourself, to be divided into units rather than units, you can use int to handle:
Public Static void Main (string[] args) { int itemsbought = 0; int funds = +; for (int price = ten; funds >= price, price + =) { itemsbought++ ; -= Price ; } + "items bought." ); System.out.println ("money left over: $" + funds);}
The result is the same as with BigDecimal.
Summary: For calculations that require precise answers, you cannot use float or double,bigdecimal to allow full control rounding, and if business requirements involve multiple rounding methods, it is convenient to use BigDecimal, and if performance is critical, the values involved are small, You can use int or float, if the range of values is not more than 9 decimal digits, you can use int, if not more than 18 digits, use long, if the value may exceed 18 bits, you must use BigDecimal.
48th: If you need a precise answer, avoid using float and double