1 minute read

Introduction

In this tutorial, you will learn how to get the whole part of a number/float using the C++ programming language.

For instance, given a number (float type) such as 68.311. The whole part would be 68, so that is what we are going to achieve.

Method #1: Using std::modf

We can use the function std::modf to separate both parts of the number such as:

#include <iostream>
#include <cmath> //Important!

int main()
{
	float myFloat = 68.311;
	float wholePart;
	std::modf(myFloat, &wholePart);

	std::cout << wholePart << std::endl; //Returns 68
	return 0;
}

NOTE: Do not forget to include the cmath library, otherwise we may get the std::modf is not a member of std error.

Method #2: Using std::floor()

We can use the floor() function to only get the whole part of the number, it rounds down to the nearest integer

#include <iostream>
#include <cmath> //Important!

int main()
{
	float myFloat = 68.311;
	int whole = std::floor(myFloat); //68

	std::cout << whole << std::endl; //Returns 68
	return 0;
}

NOTE: Do not forget to include the cmath library, otherwise we may get the std::floor is not a member of std error.

References

Read more about the std::modf function here: https://en.cppreference.com/w/cpp/numeric/math/modf

Read more about the std::floor function here: https://www.cplusplus.com/reference/cmath/floor/