Does elegant way exist to convert double to long long?

Denis picture Denis · Nov 4, 2014 · Viewed 7.8k times · Source

I want to get integer part of double. But this way does not work for me:

double param, fractpart, intpart;

param = 3.14159265;
fractpart = modf (param , &intpart);
printf ("%f = %f + %f \n", param, intpart, fractpart);

It is due to the fact, that double integer may have e-notation. For example, 3.41e10 is correct double number.

My test cases is:

  • double -> long long
  • 234343.0 -> 234343
  • 3.41e10 -> 34100000000
  • 19.999999999 -> 19
  • -10.1 -> -10
  • -0.0000001 -> 0

Is there some beautiful way to complete my task?

Answer

Columbo picture Columbo · Nov 4, 2014

Truncating your result by implicit conversion should do:

std::cout << (long long)234343.0     << '\n'
          << (long long)3.41e10      << '\n'
          << (long long)19.999999999 << '\n'
          << (long long)-10.1        << '\n'
          << (long long)-0.0000001   << '\n';

Should, on your machine, output

234343
34100000000
19
-10
0

Demo.