[SOLVED] Double to Int
Hello
If I try to cast a double with one decimal place to an int like this,
- intVariable = (int)(doubleVariable*100);
- intVariable = static_cast<int>(doubleVariable*100);
I get from time to time an error with the cast. E.g. if I want to cast the double 4.2 into the int 420, I get 419 with this method. One solution would be to add 0.001 to every double, but I think this isn’t really proper. Is there some other possibility to avoid this error.
Thx for help.
12 replies
try this:
- intVariable = static_cast<int>(doubleVariable + .5f) * 100
In other words (int)1.1f = 1 and (int)1.9f = 1
http://www.cs.tut.fi/~jkorpela/round.html
try this:In other words (int)1.1f = 1 and (int)1.9f = 1
intVariable = static_cast<int>(doubleVariable + .5f) * 100
I think this piece of code will give you 400 with an input value of 4.2… The multiplication has to be inside the static_cast as well. I’d rather try :
- intVariable = static_cast<int>(doubleVariable * 100. + .5)
Note that I also changed .5f into .5, since doubleVariable is (I think) a double and not a float.
As Johan Solo said:
4.2 -> int = 4 *100 = 400;
Correctly arranged it comes to this:
- intVariable = static_cast<int>(doubleVariable *100 + .5)
That looks like the same solution as to add 0.001. The question is why does it cast a double like 420.0 to the int 419? And how can this cast error else be resolved instead of adding half or a bit of an int?
That looks like the same solution as to add 0.001. The question is why does it cast a double like 420 to the int 419? And how can this cast error else be resolved instead of adding half or a bit of an int?
It’s a bit more clever that just adding .001, it ensures that the rounding will be done properly. When you cast a double / float value into a integer, no rounding is performed, the biggest integer value smaller than your floating point value is returned (the floor function [cplusplus.com]). Another complication is that some numbers don’t have an exact representation on a float / double. For instance 0.1 is 0.00011001100110011… (see here [learncpp.com]).
Okay thx. So finally I can assume that to add 0.5 is the best method to solve this problem.
You might want to be careful. Just adding 0.5 is not always the solution. For negative numbers you run into the opposite problem.
A typical solution for rounding is:
- inline double nint (double x)
- {
- return x < 0 ? ceil (x - 0.5) : floor (x + 0.5);
- }
You must log in to post a reply. Not a member yet? Register here!




