C | C++ | Python | Control Rounding when converting Floats to Integers

I have faced this problem in the past, but had not thought of a solution yet. Was chatting with a friend lately, and he suggested a very simple idea.

The problem is that when converting Floats to Integers, they always round down. But you want them to round up sometimes, for whatever reason. You could do this :

Integer = Float + 0.5f

This will add .5 to the float number, and it will round down to either trunc (float) or trunc (float + 1).

Thus, 1.1 rounds to 1, and 1.7 to 2. You get the idea.


Post a Comment

<< Home