Priya R
Updated date Nov 04, 2023
In this blog, we will learn how to convert floating-point numbers to integers in C++ with multiple methods.

## Introduction:

Data types play a significant role in handling different kinds of data. One common data type that programmers frequently encounter is the floating-point number, represented as a float or double. Floating-point numbers allow you to work with real numbers, including both integers and fractions. However, there are scenarios when you need to convert a float to an integer, discarding the fractional part. This process can be essential in various applications, such as when dealing with financial calculations, graphical coordinates, or discrete data. In this blog, we will explore various methods to convert a float to an int in C++.

## Method 1: C++ Type Casting

The first method to convert a float to an int in C++ is by using type casting. Type casting involves explicitly changing the data type of a value. In this case, we'll cast a float to an int.

#include <iostream>

int main() {
float floatValue = 3.14159;
int intValue = static_cast<int>(floatValue);

std::cout << "Float Value: " << floatValue << std::endl;
std::cout << "Int Value: " << intValue << std::endl;

return 0;
}

### Output:

Float Value: 3.14159
Int Value: 3

In the above program, we define a float variable floatValue with the value 3.14159. To convert this float to an int, we use the static_cast operator. It tells the compiler to perform an explicit conversion from float to int. The result is that the fractional part is truncated, and we obtain an integer value, which is then stored in the intValue variable. The output demonstrates the original float value and the converted int value.

## Method 2: C++ Standard Library Functions

C++ provides standard library functions to convert floating-point numbers to integers. One of these functions is std::lround(), which rounds the float to the nearest integer and returns it as a long int.

#include <iostream>
#include <cmath>

int main() {
float floatValue = 3.14159;
int intValue = std::lround(floatValue);

std::cout << "Float Value: " << floatValue << std::endl;
std::cout << "Int Value: " << intValue << std::endl;

return 0;
}

### Output:

Float Value: 3.14159
Int Value: 3

In this program, we include the <cmath> header to access the std::lround() function. Similar to the previous method, we have a float variable floatValue. We use the std::lround() function to round the float to the nearest integer and store the result in the intValue variable. The output displays both the original float value and the rounded int value.

## Method 3: C-style Type Casting

Another way to convert a float to an int in C++ is by using C-style type casting. This method is similar to Method 1 but uses the traditional C-style casting syntax.

#include <iostream>

int main() {
float floatValue = 3.14159;
int intValue = (int)floatValue;

std::cout << "Float Value: " << floatValue << std::endl;
std::cout << "Int Value: " << intValue << std::endl;

return 0;
}

### Output:

Float Value: 3.14159
Int Value: 3

In this program, we declare a float variable floatValue with the value 3.14159. To convert the float to an int, we use C-style type casting by enclosing the target data type (int) in parentheses and directly preceding the float variable with it. The result is that the fractional part is truncated, and the integer value is stored in the intValue variable.

## Method 4: Floor and Ceil Functions

Sometimes, you might want to round a float down or up to the nearest integer. C++ provides the std::floor() and std::ceil() functions for this purpose. The std::floor() function rounds down, while the std::ceil() function rounds up.

#include <iostream>
#include <cmath>

int main() {
float floatValue = 3.14159;
int floorValue = std::floor(floatValue);
int ceilValue = std::ceil(floatValue);

std::cout << "Float Value: " << floatValue << std::endl;
std::cout << "Floor Value: " << floorValue << std::endl;
std::cout << "Ceil Value: " << ceilValue << std::endl;

return 0;
}

### Output:

Float Value: 3.14159
Floor Value: 3
Ceil Value: 4

In this program, we introduce two new variables, floorValue and ceilValue. We use the std::floor() function to round down the float to the nearest integer, storing the result in floorValue. Conversely, we use the std::ceil() function to round up the float to the nearest integer, storing the result in ceilValue. The output shows both the original float value and the rounded values using these functions.

## Method 5: Truncation

Truncation is the process of simply removing the fractional part of a floating-point number to obtain an integer value. This can be achieved by assigning the float to an int variable, which automatically truncates the value.

#include <iostream>

int main() {
float floatValue = 3.14159;
int intValue = floatValue;

std::cout << "Float Value: " << floatValue << std::endl;
std::cout << "Int Value (Truncated): " << intValue << std::endl;

return 0;
}

### Output:

Float Value: 3.14159
Int Value (Truncated): 3

In this program, we assign the float value directly to an int variable intValue. When you do this, C++ automatically performs truncation, discarding the fractional part and keeping the integer part. The output displays both the original float value and the truncated int value.

## Method 6: Custom Rounding Function

If you need more control over the rounding process, you can create a custom rounding function. For example, you can round to a specific number of decimal places or round to the nearest multiple of a given number.

#include <iostream>
#include <cmath>

int customRound(float value, int decimalPlaces) {
float factor = pow(10, decimalPlaces);
return static_cast<int>(std::round(value * factor) / factor);
}

int main() {
float floatValue = 3.14159;
int roundedValue = customRound(floatValue, 2);

std::cout << "Float Value: " << floatValue << std::endl;
std::cout << "Rounded Value (2 decimal places): " << roundedValue << std::endl;

return 0;
}

### Output:

Float Value: 3.14159
Rounded Value (2 decimal places): 3

In this program, we create a custom rounding function customRound(). This function takes two parameters: the float value to be rounded and the number of decimal places to round to. It first multiplies the float value by a factor calculated as 10 raised to the power of the desired decimal places. This effectively moves the decimal point to the right, allowing for rounding. The result is rounded using the std::round() function and then divided by the same factor to move the decimal point back to its original position. The output displays the original float value and the custom-rounded value with two decimal places.

## Method 7: Error Handling

When converting a float to an int, it's important to be aware of potential errors. For instance, if the float value is too large to be represented as an int, you may encounter overflow issues. To handle such scenarios, you can check for potential errors and take appropriate actions.

#include <iostream>
#include <limits>

int main() {
float floatValue = 1.234567e30; // A large float
int intValue;

if (floatValue < std::numeric_limits<int>::min() || floatValue > std::numeric_limits<int>::max()) {
std::cout << "Conversion Error: Float value is out of the range of int." << std::endl;
} else {
intValue = static_cast<int>(floatValue);
std::cout << "Float Value: " << floatValue << std::endl;
std::cout << "Int Value: " << intValue << std::endl;
}

return 0;
}

### Output:

Conversion Error: Float value is out of the range of int.

In this program, we define a large float value floatValue that is well beyond the representable range of an int. To handle such cases, we use an if statement to check if the float value falls within the range of an int. We do this by comparing it to the minimum and maximum values of an int, which are provided by std::numeric_limits<int>::min() and std::numeric_limits<int>::max(), respectively. If the float value is within the range, we perform the conversion and display the float and int values. Otherwise, we report a conversion error.

## Method 8: Real-World Application - Temperature Conversion

Let's explore a real-world application where converting float to int plays a crucial role. Consider a scenario where you want to convert temperatures from degrees Celsius to degrees Fahrenheit. While both Celsius and Fahrenheit temperatures can have decimal values, you might prefer to work with integers for display purposes. In such cases, converting float values to int is essential.

#include <iostream>

int celsiusToFahrenheit(float celsius) {
return static_cast<int>((celsius * 9 / 5) + 32);
}

int main() {
float celsiusTemperature = 25.5;
int fahrenheitTemperature = celsiusToFahrenheit(celsiusTemperature);

std::cout << "Celsius Temperature: " << celsiusTemperature << "°C" << std::endl;
std::cout << "Fahrenheit Temperature: " << fahrenheitTemperature << "°F" << std::endl;

return 0;
}

### Output:

Celsius Temperature: 25.5°C
Fahrenheit Temperature: 77°F

In this program, we create a function celsiusToFahrenheit() that takes a float value in degrees Celsius as input. Inside the function, we perform the temperature conversion using the formula (Celsius * 9/5) + 32 and then cast the result to an int. This ensures that the Fahrenheit temperature is represented as an integer. The output displays both the original Celsius temperature and the converted Fahrenheit temperature.

## Conclusion:

In this cblog, we have explored various methods to convert a float to an int in C++. We started with the simplest and most commonly used method, which is type casting. We also covered C++ standard library functions, C-style type casting, floor and ceil functions, truncation, custom rounding, and error handling.