[c++] C++: How to round a double to an int?

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

The answer is


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;
}

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to floating-point

Convert list or numpy array of single element to float in python Convert float to string with precision & number of decimal digits specified? Float and double datatype in Java C convert floating point to int Convert String to Float in Swift How do I change data-type of pandas data frame to string with a defined format? How to check if a float value is a whole number Convert floats to ints in Pandas? Converting Float to Dollars and Cents Format / Suppress Scientific Notation from Python Pandas Aggregation Results

Examples related to rounding

How to round a numpy array? How to pad a string with leading zeros in Python 3 Python - round up to the nearest ten How to round a Double to the nearest Int in swift? Using Math.round to round to one decimal place? How to round to 2 decimals with Python? Rounding to 2 decimal places in SQL Rounding to two decimal places in Python 2.7? Round a floating-point number down to the nearest integer? Rounding BigDecimal to *always* have two decimal places