Forums Register Login

How to round a float value to two decimal points

+Pie Number of slices to send: Send
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....
+Pie Number of slices to send: Send
This code will hopefully help you solve your problem.

+Pie Number of slices to send: Send
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".
+Pie Number of slices to send: Send
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
Poop goes in a willow feeder. Wipe with this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 7712 times.
Similar Threads
Decimals not converting to correct fractions
(int)
double precision?
rounding off in java
Loss of precision worry when using Math.pow()
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 04:00:37.