• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to round a float value to two decimal points

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hai all,
I have a float value in my java program which is used to calculate percentage. And i have to round that value to two decimal places. The conversion i am expecting is as follows
12.3476 to 12.35
12.9988 to 13.00
I tried with round(),number2str supported by Tutil class and some jstl tags also. But answer is not like i am expecting.
Is there any other API classes to do this,Or any other method?
Please help me and do reply me immediately....
 
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This code will hopefully help you solve your problem.

 
Ranch Hand
Posts: 1970
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If what you want to do is to print out the value, rounded to 2 d.p. then the example already given, using NumberFormat, is probably the right thing to do.

On the other hand, if you want to obtain a float value, rounded to 2 d.p. then converting to text and back might work but would be rather inefficient.

An alternative might be to multiply your float by 100.0, cast it to an int and consider it to be in "hundredths".
 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is what I use. It's not necessarily the best or worst method. Modifying it for 2 decimal places should be pretty easy.



Hope this helps,
jdmaddison
 
Did you miss me? Did you miss this tiny ad?
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic