Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java format BigDecimal numbers with comma and 2 decimal place

I want to format BigDecimal Numbers with comma and 2 decimal points. e.g.

Amount is: 5.0001 and formatted to: 5.00
Amount is: 999999999.999999 and formatted to: 999,999,999.99
Amount is: 1000.4999 and formatted to: 1,000.49
Amount is: 9999.089 and formatted to: 9,999.08
Amount is: 0.19999 and formatted to: 0.19
Amount is: 123456.99999999 and formatted to: 123,456.99
like image 549
AmbGup Avatar asked Sep 29 '14 14:09

AmbGup


People also ask

Does BigDecimal accept comma?

BigDecimal doesn't have a dot or a comma. You can parse a String which contains a comma and you can produce a string which contains a comma from a BigDecimal, but that doesn't mean the BigDecimal contains it.

How do you declare 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.

How do I stop rounding in BigDecimal?

math. BigDecimal. round(MathContext m) is an inbuilt method in Java that returns a BigDecimal value rounded according to the MathContext settings. If the precision setting is 0 then no rounding takes place.


2 Answers

You should use DecimalFormat:

val df: DecimalFormat = DecimalFormat("#,##0.000")
df.decimalFormatSymbols = DecimalFormatSymbols(Locale.getDefault())
df.format(BigDecimal(123456,78)); //will output 123.456,78 - depending on Locale
like image 102
Ciprian Avatar answered Oct 03 '22 02:10

Ciprian


This should be enough to get the results.

String.format("%,.2f", amount.setScale(2, RoundingMode.DOWN)); 
like image 41
AmbGup Avatar answered Oct 03 '22 04:10

AmbGup