Convert Double to Int
Convert Double to Int in C++ (5 Programs)
BeginnerTopic: String Conversion Programs
C++ Convert Double to Int Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double num = 123.789;
// Method 1: Direct casting (truncates)
int i1 = (int)num;
// Method 2: Using static_cast
int i2 = static_cast<int>(num);
// Method 3: Using floor()
int i3 = floor(num);
// Method 4: Using round()
int i4 = round(num);
cout << "Double: " << num << endl;
cout << "Integer (cast): " << i1 << endl;
cout << "Integer (static_cast): " << i2 << endl;
cout << "Integer (floor): " << i3 << endl;
cout << "Integer (round): " << i4 << endl;
return 0;
}Output
Double: 123.789 Integer (cast): 123 Integer (static_cast): 123 Integer (floor): 123 Integer (round): 124
Understanding Convert Double to Int
This program demonstrates 5 different methods to convert a double to an integer: direct casting (truncates), static_cast, floor() (rounds down), round() (rounds to nearest), and ceil() (rounds up).
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.