How to round a floating-point number to an integer in C++

1 Answer

0 votes
#include <iostream>
#include <cmath>

int main() {
    float x = 9382.4;
    int y = static_cast<int>(std::floor(x + 0.5f));
    std::cout << y << "\n";
    
    x = 9382.5;
    y = static_cast<int>(std::floor(x + 0.5f));
    std::cout << y << "\n";
}

 
 
/*
run:
 
9382
9383
 
*/
   
 

 



answered May 14, 2025 by avibootz
...