Home >Java >javaTutorial >What is BigDecimal? Create an instance of BigDecimal
The float and double types are mainly designed for scientific calculations and engineering calculations. They perform binary floating point operations and are carefully designed to provide more accurate approximate calculations over a wide range of values. of. However, they do not provide completely accurate results and should not be used where accurate results are required. Usually business calculations often require BigDecimal to calculate values with high accuracy requirements. For example,
0.07 + 0.020.58 - 0.421.005 * 10015.1 / 1000
No matter in any environment, the code needs to be converted to a binary machine The code can be recognized by the machine. When the floating point number is output directly, the accuracy will be maintained. However, when the floating point number is calculated, the accuracy may be lost. In this case, BigDecimal is needed for calculation.
1. Create BigDecimal
BigDecimal has a constructor that takes a double-precision floating point number as a parameter. In fact, when floating point numbers are passed in for calculation, the accuracy will still be lost.
= BigDecimal(1.005= BigDecimal(100= BigDecimal("1.005"= BigDecimal("100"100.49999999999998934185896359849721193313598632812500 100.500
But you can find that when you pass in a string, you get accurate results, and BigDecimal.valueOf(double val) can also get accurate results. You can see the source code of BigDecimal.valueOf(double val) below
public static BigDecimal valueOf(double val) {// Reminder: a zero double returns '0.0', so we cannot fastpath// to use the constant ZERO. This might be important enough to// justify a factory approach, a cache, or a few private// constants, later.return new BigDecimal(Double.toString(val)); }
This method first converts the parameters to String type, and then calls the constructor parameters whose parameters are String type, so when using BigDecimal, try to use new BigDecimal(String val) or BigDecimal .valueof(double val) to ensure accurate results.
2.compareTo
## Use compareTo() to compare the size of BigDecimal.
0.05).compareTo(BigDecimal.valueOf(0.040.04).compareTo(BigDecimal.valueOf(0.040.03).compareTo(BigDecimal.valueOf(0.04BigDecimal.compareTo(BigDecimal val)When BigDecimal compares Returns 1 when val is large, Returns -1 when BigDecimal is less than val, Returns 0 when BigDecimal is equal to val.
The above is the detailed content of What is BigDecimal? Create an instance of BigDecimal. For more information, please follow other related articles on the PHP Chinese website!