• Post Reply Bookmark Topic Watch Topic
  • New Topic

Format BigDecimal  RSS feed

 
Ranch Hand
Posts: 150
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I need to format a java.math.BigDecimal with any number of integers and any number of decimal places, including zero decimal places, with comma separators.

Results like
123.456
123
0.123456789
123,456,789.0123456789

Remove insignificant zeros following the decimal point.

I'm using JDK 7.

Suggestions?

Thanks,

Lou
 
author & internet detective
Marshal
Posts: 37518
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The NumberFormat class lets you specify formatting. One of its format methods takes an Object as a parameter. That Object can be a BigDecimal.
 
Lou Pelagalli
Ranch Hand
Posts: 150
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That was easy, thanks Internet Detective Marshal Jeanne!

Posting my test code and result below in case anyone cares.

Note that the default number of decimal places for NumberFormat.getInstance() is 3.

That can be changed with NumberFormat.setMaximumFractionDigits(int).

In my case
BigDecimal bd = new BigDecimal("00000123456.7891234541000");
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(bd.scale());

Thanks,

Lou



Result
fieldValue.toString() = '123456.7891234541000'
fieldValue.toPlainString() = '123456.7891234541000'
fieldValue.toEngineeringString() = '123456.7891234541000'
Formatted bd = '123,456.7891234541'
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37518
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome. I gave you a cow for taking the time to post a good example of what you learned.
 
Lou Pelagalli
Ranch Hand
Posts: 150
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you again Jeanne!

I have a cow!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!