hqt
hqt

Reputation: 30276

Java BigDecimal : How to fortmat BigDecimal

I'm using BigDecimal for counting some big real number. Although I have try two method : BigDecimal.toString() or BigDecimal.stripTrailingZeros().toString(), it still not sasitfy my requirement.

For example if I use stripTrailingZeros: 4.3000 becomes 4.3 but 4.0 becomes 4.0 not 4. Both above methods cannot sastisty those conditions. So, my question is : how to done it in java ?

Thanks :)

Upvotes: 1

Views: 343

Answers (2)

Zong
Zong

Reputation: 6230

You can use DecimalFormat as follows:

BigDecimal a = new BigDecimal("4.3000");
BigDecimal b = new BigDecimal("4.0");

DecimalFormat f = new DecimalFormat("#.#");
f.setDecimalSeparatorAlwaysShown(false)
f.setMaximumFractionDigits(340);

System.out.println(f.format(a));
System.out.println(f.format(b));

which prints

4.3
4

As Bhashit pointed out, the default number of fractional digits is 3, but we can set it to the maximum of 340. I actually wasn't aware of this behaviour of DecimalFormat. This means that if you need more than 340 fractional digits, you'll probably have to manipulate the string given by toString() yourself.

Upvotes: 3

Bhashit Parikh
Bhashit Parikh

Reputation: 3131

Look into the DecimalFormat class. I think what you want is something like

DecimalFormat df = new DecimalFormat();
// By default, there will a locale specific thousands grouping. 
// Remove the statement if you want thousands grouping.
// That is, for a number 12345, it is printed as 12,345 on my machine 
// if I remove the following line.
df.setGroupingUsed(false);
// default is 3. Set whatever you think is good enough for you. 340 is max possible.
df.setMaximumFractionDigits(340);
df.setDecimalSeparatorAlwaysShown(false);
BigDecimal bd = new BigDecimal("1234.5678900000");
System.out.println(df.format(bd));
bd = new BigDecimal("1234.00");
System.out.println(df.format(bd));

Output:
1234.56789
1234

You can also use a RoundingMode of your choice. Control the number of decimal points to be shown by using the pattern provided to the DecimalFormat constructor. See the DecimalFormat documentation for more formatting details.

Upvotes: 3

Related Questions