Offirmo
Offirmo

Reputation: 19870

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)

Upvotes: 6

Views: 19373

Answers (3)

Victor Sand
Victor Sand

Reputation: 2340

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.

Upvotes: 8

Mike B
Mike B

Reputation: 478

You could also consider

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

lexical_cast has the benefit of working for all primitive types, and stl strings etc. It also means you don't have to do the (float_value + 0.5) stuff.

Upvotes: 1

taocp
taocp

Reputation: 23664

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++.

Upvotes: 1

Related Questions