Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigDecimal with at least two decimals

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.

like image 539
Alex H Avatar asked Dec 07 '15 13:12

Alex H


People also ask

Can BigDecimal have decimals?

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.

How do you restrict a float upto 2 decimal places?

We will use %. 2f to limit a given floating-point number to two decimal places.

How do I restrict 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.


1 Answers

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.

like image 100
Tunaki Avatar answered Sep 28 '22 03:09

Tunaki