jQuery in Action, 2nd edition
The moose likes Java in General and the fly likes How to round a float value to two decimal points Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "How to round a float value to two decimal points" Watch "How to round a float value to two decimal points" New topic
Author

How to round a float value to two decimal points

Abhilash
Greenhorn

Joined: Nov 02, 2004
Posts: 12
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

Joined: Mar 18, 2003
Posts: 118
This code will hopefully help you solve your problem.

Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
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".


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P
Joseph Maddison
Ranch Hand

Joined: Nov 04, 2004
Posts: 53
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to round a float value to two decimal points
 
Similar Threads
Loss of precision worry when using Math.pow()
(int)
double precision?
rounding off in java
Decimals not converting to correct fractions