Advertisement

Rounding a number

Started by May 15, 2003 02:16 PM
8 comments, last by de_matt 21 years, 9 months ago
I wrote some code for motion in C++. However, the movement per frame is so small that it seems to screw up smehow. How do I round the number? It''s of type FLOAT
multiply by the 10^ however many decimal places you want, truncate, then divide by the 10^ whatever.

[edited by - fadilthrejk on March 19, 2002 at 4:53 AM]
Advertisement
Thanks, just what I wanted
It''s easier like this:

int roundedNum = int(floatNum + 0.5f);
So it is easier to copy and paste someone else''s code than to actually read and understand the solution given by someone else? Because fadilthrejk''s solution was the same thing, only more general...
Yes but he said C++ was his language, so I gave it to him in that. Also the previous method used multiplication and division, which is unneccassary.
Advertisement
Not really, he was saying how to round to a specific decimal place. Your code rounds to the nearest integer, whereas he might need to round it to the nearest hundredths place. To do this, you''d have to multiply and divide as he said.
I am no expert programmer, however, I followed the directions given on this post and it seems as if the directions given do not "Round" the number, they simply lower the amount of decimal places. For example, I wanted the number 6.256 to be rounded to the second decimal place, in other words, I wanted the number to be 6.26. However, when I followed the directions given above, I recieved the number 6.25, which isn't correct. Here is the math that I used to prove my statement

6.256*(10^2)= 625.6

625.6 truncated = 625

625/(10^2)= 6.25

As you can see, the rounded number is not the correct 6.26, but it is the same number with fewer decimal places. Am I doing something wrong with my math? If so, please correct me.
Thanks,

--BioagentX

[edited by - BioagentX on May 17, 2003 10:41:43 PM]

[edited by - BioagentX on May 17, 2003 10:44:17 PM]
There are three types of people in this world, those who can count, and those who can't
You''re perfectly right. If you want your rounding to inflect at the halfway point, add 0.5 right between multiplying and truncating. (note that this will cause issues with negative numbers; if this is a problem for you, I can tell you a more robust method.)


How appropriate. You fight like a cow.
it will always do that unless you change the rounding mode.

To the vast majority of mankind, nothing is more agreeable than to escape the need for mental exertion... To most people, nothing is more troublesome than the effort of thinking.
To the vast majority of mankind, nothing is more agreeable than to escape the need for mental exertion... To most people, nothing is more troublesome than the effort of thinking.

This topic is closed to new replies.

Advertisement