C ++ How to properly round const float to unsigned int

So I have a const-float that has a range of 0.0 to 1.0. What is the correct way to apply this to unsigned int by rounding or truncating?

Will this be acceptable?

const float f=0.5f;
unsigned int i=static_cast<unsigned int>(f);

      

+3


source to share


2 answers


Yes, this is perfectly acceptable if you want to truncate and if you don't care what happens with negative numbers or overflow.

If you want to round, call first roundf

(or, if you want a different rounding rule than half rounds from zero, write your own code).

If you want to deal with negative numbers or overflow, you need to check before converting.

In accordance with 5.2.9, the standard static_cast

in this case is defined in the same way as unsigned int i(f)

. And I think most style guides agree on which is preferable static_cast

(since bringing clarity and visibility is usually a good thing).

More details:



According to 4.9.1:

A floating point value can be converted to an integer prvalue. The conversion is transcribed; those. the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the target type.

I don't know exactly how const-away works in C ++ 14, but I believe this is not a qualification conversion, but part of the lvalue-to-rval conversion from 4.1.1:

A gl (3.10) value of a non-functional type without an array T can be converted to a prvalue ... If T is a non-class type, then prvalue is a cv-unqualified version of T.

So, f

has one lvalue-to-rval conversion from lvalue const float

to rvalue float

, then one floating integral conversion from float

to unsigned int

, so by 4.0.1 it is a standard conversion, so in 5.2.9 it acts like static_cast

.

+4


source


Just add half to the round:

unsigned int i = static_cast<unsigned int>(f + 0.5);

      



Or not cut anything - what you have is good (provided f >= 0

)

unsigned int i = static_cast<unsigned int>(f);

      

+3


source







All Articles