In C++, the double data type is used to store floating-point numbers with double precision. In this article, we will learn how to round a double value to an int in C++.
Example:
Input:
double val= 2.6
Output:
Integer for double value 2.5 is: 3 Rounding a Double to an Int in C++To round a double value to a nearest integer value we can use the std::round() function from the <cmath> library , we have to pass a double value as a parameter to this function and it computes the nearest integer value for it.
Syntax of std::round()int intValueName = round(doubleValue); C++ Program to Round a Double to an intThe following program demonstrates how to round a double value to an int in C++.
C++
// C++ program to demonstrates how to round a double value
// to an int
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
// Define double values
double doubleValue1 = 2.5;
double doubleValue2 = 9.99;
// rounding the double values to int type
int intValue1 = round(doubleValue1);
cout << "The integer for double value " << doubleValue1
<< " is " << intValue1 << endl;
int intValue2 = round(doubleValue2);
cout << "The integer for double value " << doubleValue2
<< " is " << intValue2 << endl;
return 0;
}
OutputThe integer for double value 2.5 is 3
The integer for double value 9.99 is 10
Time Complexity: O(1) Auxilliary Space: O(1)
|