This week's book giveaway is in the Programmer Certification forum.
We're giving away four copies of OCP Oracle Certified Professional Java SE 21 Developer (Exam 1Z0-830) Java SE 17 Developer (Exam 1Z0-829) Programmer’s Guide and have Khalid Mughal and Vasily Strelnikov on-line!
See this thread for details.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

format decimal numbers

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 625
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 334
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here is the code which works for me.
DecimalFormat df = new DecimalFormat("0.##");
df.format(theNumberToFormat);
Hope it help
 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic