Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a float to an int in modern C++

As strange as it may seems, I can't find how to cleanly convert a float to an int.

This technique

int int_value = (int)(float_value + 0.5);

triggers a

warning: use of old-style cast

in gcc.

So, what is the modern-style, simple way to convert a float to an int ? (I accept the loss of precision of course)

like image 811
Offirmo Avatar asked May 15 '13 16:05

Offirmo


2 Answers

As Josh pointed out in the comments, + 0.5 is not very reliable. For extra security you could combine a static_cast with std::round like so:

int int_value = static_cast<int>(std::round(float_value));

For the casting part, see this excellent post for an explanation.

like image 192
Victor Sand Avatar answered Sep 19 '22 22:09

Victor Sand


try:

int int_value = static_cast<int>(float_value + 0.5);

FYI: different casts in C++ gave a very good explanation about those 4 casts introduced in C++.

like image 20
taocp Avatar answered Sep 20 '22 22:09

taocp