Horje
How to Round a Double to an int in C++?

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 int

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

Output
The 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)






Reffered: https://www.geeksforgeeks.org


C++

Related
How to Declare a Global Variable in C++? How to Declare a Global Variable in C++?
C++ Program to Implement Stack using array C++ Program to Implement Stack using array
How to Convert Char Array to Int in C++ How to Convert Char Array to Int in C++
How to Convert Float to int in C++? How to Convert Float to int in C++?
How to Convert ASCII Value into char in C++? How to Convert ASCII Value into char in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13