How to Create BigDecimal Objects in Java
To create a BigDecimal object in Java, you call one of the constructors you see below. Each of these constructors takes a value and converts it to a BigDecimal object.
Although you can create BigDecimal values from a double or float value, it’s not recommended. The whole point of using BigDecimal is to avoid the accuracy errors that are inherent with double and float values, and the only way to do that is to avoid using double and float altogether. As the old computer saying reminds you, "Garbage In, Garbage Out."
|BigDecimal(double val)||Creates a BigDecimal from the double value.|
|BigDecimal(float val)||Creates a BigDecimal from the float value.|
|BigDecimal(int val)||Creates a BigDecimal from the int value.|
|BigDecimal(long val)||Creates a BigDecimal from the long value.|
|BigDecimal(String val)||Creates a BigDecimal from the String value. The string must contain a valid representation of a decimal number.|
Take these statements, for example:
BigDecimal value = new BigDecimal(0.01); System.out.println(value);
Here’s what gets printed on the console:
The best way to create a BigDecimal object with an initial decimal value is via a string, like this:
BigDecimal value = new BigDecimal("0.01");
Here, value has a value of exactly 0.01.
If the initial value is an integer, you can safely pass it to the constructor. Remember that integers don’t have the same accuracy problems that doubles and floats do. Also, you can convert a BigDecimal to a double solely for the purpose of using the NumberFormat class to format the result. As long as you don’t use the double in any calculations, you won’t have to worry about floating-point inaccuracies.
Note: The BigDecimal class has no default constructor because you can’t have a BigDecimal object without a value.