-3

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. ;

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
Gabriel
  • 75
  • 2
  • 9
  • 3
    There is not always a clear number of decimal digits, because a floating point number is usually represented as (equivalent to) a fraction of integers a/b, where b is a power of 2. But you can do this by *specifying* the number of digits you want. E.g., for 5 digits, multiply the decimals part by 10 000, and convert to integer. – Cheers and hth. - Alf Feb 28 '16 at 12:19

3 Answers3

1

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • So i must create a function that returns(an int e for example) the size of X , then multiply x with 10^e; – Gabriel Feb 28 '16 at 12:26
1

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.

Community
  • 1
  • 1
mindriot
  • 5,413
  • 1
  • 25
  • 34
1

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;
}
GhaziBenDahmane
  • 548
  • 3
  • 15