Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to cast to int from std::round?

I have a question about std::round with signature: double round (double x);

Let's say I have this code:

int i = std::round(0.9);

In this case, std::round should return 1.00000000000, but that's uncomfortably close to 0.9999999999999 and I'm concerned that floating-point errors will end up rounding this down.

I would hope that i == 1, but is this guaranteed?

like image 256
Stewart Avatar asked Nov 07 '17 08:11

Stewart


Video Answer


1 Answers

The std::round function returns a floating point value, "rounding halfway cases away from zero". As with any double to int implicit conversion the compiler will issue a warning:

conversion from 'double' to 'int', possible loss of data

Use std::lround or std::lrint if you want to return an integral value.

like image 99
Ron Avatar answered Sep 22 '22 19:09

Ron