I'm looking for a function that returns the decimals part of a number(but not like 0.numbers), for example :
float x=12.3456;
I want it to return :
int i=3456;
I tried
x=x-(int)x;
i=x;
But it returns 0. ;
I'm looking for a function that returns the decimals part of a number(but not like 0.numbers), for example :
float x=12.3456;
I want it to return :
int i=3456;
I tried
x=x-(int)x;
i=x;
But it returns 0. ;
Lets take these two assignments one by one
x=x-(int)x;
i=x;
First you do x=x-(int)x
which will result in x
being equal to 0.346
. Then you do i=x
which truncates (i.e. remove the decimals) of the value of x
leading to i
becoming zero.
You need to multiply x
by 1000
before the assignment to i
:
i = 1000 * x;
The number 1000
depends on the number of digits of decimals you want. More zeros means more digits.
To add to Joachim Pileborg's answer: if you really want to have all fractional digits in your integer, you could do something like this:
#include <iostream>
#include <iomanip>
#include <limits>
#include <cmath>
template <typename T>
long long fractional(T val)
{
T frac = val - std::floor(val);
long long alldigits(std::pow(10, std::numeric_limits<T>::digits10)*frac);
while (alldigits%10 == 0)
{
alldigits /= 10;
}
return alldigits;
}
int main()
{
std::cout << fractional<float>(1.0/8.0) << std::endl; // 125
std::cout << fractional<float>(1.0/3.0) << std::endl; // 333333
std::cout << fractional<double>(1.0/3.0) << std::endl; // 333333333333333
return 0;
}
Live example here. But the example also shows the problems you'd run into: depending on the number and the precision of the underlying data type, you would get different amounts of digits, which ends up being difficult to interpret. So most likely, getting a fixed number of digits is going to be the better solution.
you could try this :
#include <iostream>
int intpart(float x) {
float b = 0;
x -= (int)x;
while (x - (int)x != 0)
x *= 10;
return (int)x;
}
int main(int argc, char const *argv[])
{
std::cout << intpart(17.5) << std::endl;
return 0;
}