I have a double (call it x), meant to be 55 but in actuality stored as 54.999999999999943157 which I just realised.
So when I do
double x = 54.999999999999943157;
int y = (int) x;
y = 54 instead of 55!
This puzzled me for a long time. How do I get it to correctly round?
This question is related to
c++
floating-point
rounding
Casting is not a mathematical operation and doesn't behave as such. Try
int y = (int)round(x);
It is worth noting that what you're doing isn't rounding, it's casting. Casting using (int) x
truncates the decimal value of x
. As in your example, if x = 3.9995
, the .9995
gets truncated and x = 3
.
As proposed by many others, one solution is to add 0.5
to x
, and then cast.
Casting to an int
truncates the value. Adding 0.5
causes it to do proper rounding.
int y = (int)(x + 0.5);
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x=54.999999999999943157;
int y=ceil(x);//The ceil() function returns the smallest integer no less than x
return 0;
}
Source: Stackoverflow.com