Check if float is a whole number in C++
Introduction
In this tutorial, you will learn how to check if a float value is a whole number in the C++ programming language. We will be using mathematical operations such as casting to an int, and using the modulo operator to check if the float value is a whole number or not.
Method #1: Using the std::floor function
We can use the std::floor
function to floor a float to the nearest integer and compare it to the original float. If it is equal, then the original float is a whole number. Otherwise, then we can assume it isn’t a whole number.
#include <iostream>
#include <cmath>
int main(){
float x = 3.5f;
if(std::floor(x) == x){
std::cout << x << " is a whole number" << std::endl;
} else {
std::cout << x << " is not a whole number" << std::endl;
}
return 0;
}
In this example, x = 3.5 is not a whole number, so the output will be “3.5 not is a whole number”.
Method #2: Using std::fmod()
std::fmod()
is a function from the cmath library in C++ that returns the floating-point remainder of dividing x by y. It calculates the remainder of the division of x by y in a way that is similar to the remainder operator (%), but with the added feature that it works with floating-point numbers.
It takes two arguments, the dividend and the divisor, and returns the remainder as a double. The function can be useful when working with mathematical operations that involve floating-point numbers and the need to get the remainder of a division.
Therefore, we can also use the std::fmod()
function to check if the remainder of the float value divided by 1 is equal to 0. If it is, then the float value is a whole number.
#include <iostream>
#include <cmath>
int main(){
float x = 3.5f;
if(std::fmod(x, 1) == 0){
std::cout << x << " is a whole number" << std::endl;
} else {
std::cout << x << " is not a whole number" << std::endl;
}
return 0;
}
In this example, x = 3.5 is not a whole number, so the output will be “3.5 not is a whole number”.
Conclusion
In this tutorial, you have learned two methods of how to check if a float value is a whole number in C++. You can use the std:floor()
function or the std::fmod()
function to check if the remainder of the float value divided by 1 is equal to 0. If it is, then the float value is a whole number.