hello
here is the problem.I want to round off a float as follow
1.2 to 1
1.5 to 1 or 2
1.7 to 2
could any suggest what function to use. I am writing code in
C using Microsoft visual studio 2005
hello
here is the problem.I want to round off a float as follow
1.2 to 1
1.5 to 1 or 2
1.7 to 2
could any suggest what function to use. I am writing code in
C using Microsoft visual studio 2005
the round function does not work in visual studio 2005. I tried and got a error message.
thanks
So round is somewhat new, yes; you should certainly have floor in math.h, which returns the next lowest integer, so you'll have to massage the input first.
Adding 0.5 and getting the lowest integer should do the trick, right?
Yep, that's the best way if you only have truncation available to you. Be aware though that if you have a floating point inaccuracy, you might get undesired results.
e.g. if you have 6.4999999999999999 and you add 0.5, you get 6.99999999999999, which when floored is 6 not 7.
One way to get around this is to add an epsilon value. Take the smallest number of decimal places you care about (say 5) add two more decimal places and then add 10^-x to your number:
e.g. if you have 6.4999999999 + 0.0000001 = 6.5 6.5 + 0.5 = 7
QuantumPete
"No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
"Have you tried turning it off and on again?" - The IT Crowd