Reputation: 15
I am currently using the BigDecimal and with variable number of digits after decimal point. I need to be able to format the number with loosing the number of digits which I had set, because when I use format then it reduces the decimal digits to 2 - 4.
str1 =bigDecimal.setScale(numberOfDecimalPlaces, RoundingMode.HALF_UP);
str2 = NumberFormat.getInstance().format(bigDecimal.setScale(numberOfDecimalPlaces, RoundingMode.HALF_UP));
The first list works fine but when I want to format the String/BigDecimal then it drops the decimal places.
Note: Decimal place will vary from 0 to 15(from user). I am using Android Studio-API15/Java. Precision is important in my app, formatting is to improve readability.
Upvotes: 1
Views: 4812
Reputation: 16043
As mentioned by @JB Nizet, you need to tune NumberFormat acc. to your need.
Below is a working example:
int numberOfDecimalPlaces = 6;
BigDecimal bigDecimal = new BigDecimal(11212.122323);
bigDecimal.setScale(numberOfDecimalPlaces, RoundingMode.HALF_UP);
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setMinimumFractionDigits(numberOfDecimalPlaces);
System.out.println(numberFormat.format(bigDecimal));
Output:
11,212.122323
Upvotes: 3