• Post Reply Bookmark Topic Watch Topic
  • New Topic

format decimal numbers  RSS feed

 
jenny wang
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I have decimal numbers as
"10.35009", "11.4765",
I need a method to format these two numbers into
"10.35" and "11.47".
Thanks in advance!
Jenny
 
Sean Casey
Ranch Hand
Posts: 625
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you could use DecimalFormat class. I think it is in java.util.
Here's an example of it in a book I'm looking at:
DecimalFormat twoDigits= new DecimalFormat("#0.00");
and then there is a fomat(),

so twoDigits.format(the number goes here);
I'm sorry if that isn't a good explanantion. Check out that package though. I would explain it better if I had more time.
 
ruilin yang
Ranch Hand
Posts: 334
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the code which works for me.
DecimalFormat df = new DecimalFormat("0.##");
df.format(theNumberToFormat);
Hope it help
 
Julio Lopez
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or you could use the java.math.BigDecimal class,
java.math.BigDecimal aBigDecimal = new java.math.BigDecimal(10.35009);
java.math.BigDecimal anotherBigDecimal = new java.math.BigDecimal(11.4765);
aBigDecimal = aBigDecimal.setScale(2, java.math.BigDecimal.ROUND_HALF_UP);
anotherBigDecimal = anotherBigDecimal.setScale(2, java.math.BigDecimal.ROUND_HALF_UP);

Julio Lopez
M-Group Systems

 
jenny wang
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well, my original question is getting decimal number but NOT ROUND it which means 11.4765 should get "11.47" instead of "11.48".
jenny
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!