How to convert float to int in modern C ++

Oddly enough, I can't find how to cleanly convert a float to int .

This method

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

starts up

 warning: use of old-style cast 

in gcc.

So what is modern style, an easy way to convert float to int ? (I agree with the loss of accuracy, of course)

+4
source share
3 answers

As Josh noted in the comments, + 0.5 not very reliable. For added security, you can combine static_cast with std::round like this:

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

For the casting part, see this great article for an explanation.

+4
source

to try:

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

FYI: various translations in C ++ gave a very good explanation about the 4 casts introduced in C ++.

+1
source

You can also consider

 int int_value = boost::lexical_cast<int>(float_value); 

lexical_cast has the advantage of working for all primitive types, stl strings, etc. It also means that you do not need to do (float_value + 0.5).

+1
source

Source: https://habr.com/ru/post/1480991/


All Articles