programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# format decimal numbers

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

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.

Ranch Hand
Posts: 334
Here is the code which works for me.
DecimalFormat df = new DecimalFormat("0.##");
df.format(theNumberToFormat);
Hope it help

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

 Don't get me started about those stupid light bulbs.