# format decimal numbers

jenny wang
Greenhorn
Posts: 27

I have decimal numbers as
"10.35009", "11.4765",
I need a method to format these two numbers into
"10.35" and "11.47".
Jenny

Sean Casey
Ranch Hand
Posts: 625
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
Here is the code which works for me.
DecimalFormat df = new DecimalFormat("0.##");
df.format(theNumberToFormat);
Hope it help

Julio Lopez
Greenhorn
Posts: 28
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
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