Decimal part of a number in C++
Introduction
In this tutorial, you will learn how to get the decimal part of a number/float using the C++ programming language.
For instance, given a number (float type) such as 12.351. The fractional part would be 0.351, so that is what we are going to achieve.
Method #1: Using std::floor()
We can use the floor() function to subtract the whole part of the number, which would result in the decimal part only:
#include <iostream>
#include <cmath>
int main()
{
float myFloat = 12.351;
float whole = std::floor(myFloat); //12
float fractional = myFloat - whole; //12.351 - 12 = 0.351
std::cout << fractional << std::endl; //Returns 0.351
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::floor function here: https://www.cplusplus.com/reference/cmath/floor/