I try to multiply an integer by a double but I obtain a wrong result. In my example the result of v * decimals
is 11.9999999999...
instead of 12
although when I print it using cout
it shows 12
(I see the value using gdb), then static_cast
set 11
in uint64_t a
. Why does this happen? What is the correct way to multiply an integer and a double?
#include <iostream>
int main(int argc, char *argv[])
{
const uint64_t decimals = 100000000;
double v = 0.00000012;
uint64_t a = 0;
std::cout << "Initial value=" << v << std::endl;
v = v * decimals;
std::cout << "v * decimals=" << v << std::endl;
a = static_cast<uint64_t>(v);
std::cout << "a=" << a << std::endl;
return 0;
}
output:
Initial value=1.2e-07
v * decimals=12
a=11