Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a number with always 2 decimal points using BigDecimal?

I am using BigDecimal to get some price values. Requirement is something like this, what ever the value we fetch from database, the displayed valued should have 2 decimal points.

Eg:

fetched value is 1 - should be displayed as 1.00
fetched value is 1.7823 - should be displayed as 1.78

I am using setScale(2, BigDecimal.ROUND_HALF_UP) but still some places, if the data from DB is a whole number then the same is being displayed !!

I mean if the value is 0 from DB its displayed as 0 only. I want that to be displayed as 0.00

Thanks

like image 882
user1391730 Avatar asked Jan 25 '13 05:01

user1391730


People also ask

How do you keep a float up to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you correct to 2 decimal places in Java?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places. /* Code example to print a double to two decimal places with Java printf */ System.

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.


2 Answers

BigDecimal is immutable, any operation on it including setScale(2, BigDecimal.ROUND_HALF_UP) produces a new BigDecimal. Correct code should be

BigDecimal bd = new BigDecimal(1); bd.setScale(2, BigDecimal.ROUND_HALF_UP); // this does change bd bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP); System.out.println(bd); 

output

1.00 

Note - Since Java 9 BigDecimal.ROUND_HALF_UP has been deprecated and you should now use RoundingMode.ROUND_HALF_UP.

like image 115
Evgeniy Dorofeev Avatar answered Sep 17 '22 01:09

Evgeniy Dorofeev


you can use the round up format

BigDecimal bd = new BigDecimal(2.22222); System.out.println(bd.setScale(2,BigDecimal.ROUND_UP)); 

Hope this help you.

like image 24
corgrin Avatar answered Sep 17 '22 01:09

corgrin