• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to round a float value to two decimal points  RSS feed

 
Abhilash
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • 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....
 
Jonas Isberg
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code will hopefully help you solve your problem.

 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • 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".
 
Joseph Maddison
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • 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
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!