Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int64_t to double

  int64_t a = 1234;

  double d = (double) a;

Is this the recommended way?

like image 704
kal Avatar asked Mar 28 '09 01:03

kal


People also ask

Can Double hold uint64?

According to Wikipedia, you can store 15.95 decimal digits in a 64-bit IEEE 754 floating-point number. double has typically up to 53 bits precision, compared to 64.

What does int64_t mean?

A long on some systems is 32 bits (same as an integer), the int64_t is defined as a 64 bit integer on all systems (otherwise known as a long long). Portability may be affected using long, but using int64_t looks like it was created to increase portability.


2 Answers

use static_cast as strager answers. I recommend against using the implicit cast (or even a C-style cast in C++ source code) for a few reasons:

  • Implicit casts are a common source of compiler warnings, meaning you may be adding noise to the build (either now, or later when better warning flags are added).
  • The next maintenance programmer behind you will see an implicit cast, and needs to know if it was intentional behavior or a mistake/bug. Having that static_cast makes your intent immediately obvious.
  • static_cast and the other C++-style casts are easy for grep to handle.
like image 68
Tom Avatar answered Oct 17 '22 08:10

Tom


You should use static_cast or rely on the implicit cast instead:

int64_t a = 1234;
double d = static_cast<double>(a);
double f = a;
like image 35
strager Avatar answered Oct 17 '22 07:10

strager