I have BigDecimal
values and I want to have them at least two decimal digits, but I don't want to trim the rest.
So 3
should result in 3.00
, but 3.001
should stay 3.001
.
I know that I can do this by simply adding 0.00
:
new BigDecimal("3").add(new BigDecimal("0.00")) //=> 3.00
new BigDecimal("3.001").add(new BigDecimal("0.00")) //=> 3.001
Is there a build in method or a more elegant way to do this?
I can't use setScale
, because I want to keep additional decimals when they exist.
Immutable, arbitrary-precision signed decimal numbers. A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point.
We will use %. 2f to limit a given floating-point number to two decimal places.
Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.
Actually, you still can use setScale
, you just have to check if the current scale if greater than 2 or not:
public static void main(String[] args) {
BigDecimal bd = new BigDecimal("3.001");
bd = bd.setScale(Math.max(2, bd.scale()));
System.out.println(bd);
}
With this code, a BigDecimal
that has a scale lower than 2 (like "3"
) will have its scale set to 2, and if it's not, it will keep its current scale.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With