How can I convert an integer to float with rounding towards zero?

Viewed 4324

When an integer is converted to floating-point, and the value cannot be directly represented by the destination type, the nearest value is usually selected (required by IEEE-754).

I would like to convert an integer to floating-point with rounding towards zero in case the integer value cannot be directly represented by the floating-point type.

Example:

int i = 2147483647;
float nearest = static_cast<float>(i);  // 2147483648 (likely)
float towards_zero = convert(i);        // 2147483520
9 Answers

Since C++11, one can use fesetround(), the floating-point environment rounding direction manager. There are four standard rounding directions and an implementation is permitted to add additional rounding directions.

#include <cfenv> // for fesetround() and FE_* macros
#include <iostream> // for cout and endl
#include <iomanip> // for setprecision()

#pragma STDC FENV_ACCESS ON

int main(){
    int i = 2147483647;

    std::cout << std::setprecision(10);

    std::fesetround(FE_DOWNWARD);
    std::cout << "round down         " << i << " :  " << static_cast<float>(i) << std::endl;
    std::cout << "round down        " << -i << " : " << static_cast<float>(-i) << std::endl;

    std::fesetround(FE_TONEAREST);
    std::cout << "round to nearest   " << i << " :  " << static_cast<float>(i) << std::endl;
    std::cout << "round to nearest  " << -i << " : " << static_cast<float>(-i) << std::endl;

    std::fesetround(FE_TOWARDZERO);
    std::cout << "round toward zero  " << i << " :  " << static_cast<float>(i) << std::endl;
    std::cout << "round toward zero " << -i << " : " << static_cast<float>(-i) << std::endl;

    std::fesetround(FE_UPWARD);
    std::cout << "round up           " << i << " :  " << static_cast<float>(i) << std::endl;
    std::cout << "round up          " << -i << " : " << static_cast<float>(-i) << std::endl;

    return(0);
}

Compiled under g++ 7.5.0, the resulting executable outputs

round down         2147483647 :  2147483520
round down        -2147483647 : -2147483648
round to nearest   2147483647 :  2147483648
round to nearest  -2147483647 : -2147483648
round toward zero  2147483647 :  2147483520
round toward zero -2147483647 : -2147483520
round up           2147483647 :  2147483648
round up          -2147483647 : -2147483520
  • Omitting the #pragma doesn't seem to change anything under g++.

  • @chux comments correctly that the standard doesn't explicitly state that fesetround() affects rounding in static_cast<float>(i). For a guarantee that the set rounding direction affects the conversion, use std::nearbyint and its -f and -l variants. See also std::rint and its many type-specific variants.

  • I probably should have looked up the format specifier to use a space for positive integers and floats, rather than stuffing it into the preceding string constants.

  • (I haven't tested the following snippet.) Your convert() function would be something like

    float convert(int i, int direction = FE_TOWARDZERO){
        float retVal = 0.;
        int prevdirection = std::fegetround();
        std::fesetround(direction);
        retVal = static_cast<float>(i);
        std::fesetround(prevdirection);
        return(retVal);
    }
    

You can use std::nextafter.

int i = 2147483647;
float nearest = static_cast<float>(i);  // 2147483648 (likely)
float towards_zero = std::nextafter(nearest, 0.f);        // 2147483520

But you have to check, if static_cast<float>(i) is exact, if so, nextafter would go one step towards 0, which you probably don't want.

Your convert function might look like this:

float convert(int x){
    if(std::abs(long(static_cast<float>(x))) <= std::abs(long(x)))
        return static_cast<float>(x);
    return std::nextafter(static_cast<float>(x), 0.f);
}

It may be that sizeof(int)==sizeof(long) or even sizeof(int)==sizeof(long long) in this case long(...) may behave undefined, when the static_cast<float>(x) exceeds the possible values. Depending on the compiler it might still work in this cases.

A C implementation dependent solution that I am confident has a C++ counterpart.


Temporarily change the rounding mode the conversion uses that to determine which way to go in inexact cases.

the nearest value is usually selected (required by IEEE-754).

Is not entirely accurate. The inexact case is rounding mode dependent.

C does not specify this behavior. C allows this behavior, as it is implementation-defined.

If the value being converted is in the range of values that can be represented but cannot be represented exactly, the result is either the nearest higher or nearest lower representable value, chosen in an implementation-defined manner.

#include <fenv.h>

float convert(int i) {
   #pragma STDC FENV_ACCESS ON
   int save_round = fegetround();
   fesetround(FE_TOWARDZERO);
   float f = (float) i;
   fesetround(save_round);
   return f;
}

I understand the question to be restricted to platforms that use IEEE-754 binary floating-point arithmetic, and where float maps to IEEE-754 (2008) binary32. This answer assumes this to be the case.

As other answers have pointed out, if the tool chain and the platform supports this, use the facilities supplied by fenv.h to set the rounding mode for the conversion as desired.

Where those are not available, or slow, it is not difficult to emulate the truncation during int to float conversion. Basically, normalize the integer until the most significant bit is set, recording the required shift count. Now, shift the normalized integer into place to form the mantissa, compute the exponent based on the normalization shift count, and add in the sign bit based on the sign of the original integer. The process of normalization can be sped up significantly if a clz (count leading zeros) primitive is available, maybe as an intrinsic.

The exhaustively tested code below demonstrates this approach for 32-bit integers, see function int32_to_float_rz. I successfully built it as both C and C++ code with the Intel compiler version 13.

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <fenv.h>

float int32_to_float_rz (int32_t a)
{
    uint32_t i = (uint32_t)a;
    int shift = 0;
    float r;
    // take absolute value of integer
    if (a < 0) i = 0 - i;
    // normalize integer so MSB is set
    if (!(i > 0x0000ffffU)) { i <<= 16; shift += 16; }
    if (!(i > 0x00ffffffU)) { i <<=  8; shift +=  8; }
    if (!(i > 0x0fffffffU)) { i <<=  4; shift +=  4; }
    if (!(i > 0x3fffffffU)) { i <<=  2; shift +=  2; }
    if (!(i > 0x7fffffffU)) { i <<=  1; shift +=  1; }
    // form mantissa with explicit integer bit 
    i = i >> 8;
    // add in exponent, taking into account integer bit of mantissa
    if (a != 0) i += (127 + 31 - 1 - shift) << 23;
    // add in sign bit
    if (a < 0) i |= 0x80000000;
    // reinterpret bit pattern as 'float'
    memcpy (&r, &i, sizeof r);
    return r;
}

#pragma STDC FENV_ACCESS ON

float int32_to_float_rz_ref (int32_t a)
{
    float r;
    int orig_mode = fegetround ();
    fesetround (FE_TOWARDZERO); 
    r = (float)a;
    fesetround (orig_mode); 
    return r;
}

int main (void) 
{
    int32_t arg;
    float res, ref;

    arg = 0;
    do {
        res = int32_to_float_rz (arg);
        ref = int32_to_float_rz_ref (arg);
        if (res != ref) {
            printf ("error @ %08x: res=% 14.6a  ref=% 14.6a\n", arg, res, ref);
            return EXIT_FAILURE;
        }
        arg++;
    } while (arg);
    return EXIT_SUCCESS;
}

A specified approach.


"the nearest value is usually selected (required by IEEE-754)" implies OP expects IEEE-754 is involved. Many C/C++ implementation do follow much of IEEE-754, yet adherence to that spec is not required. The following relies on C specifications.

Conversion of an integer type to a floating point type is specified as below. Notice conversion is not specified to depend on rounding mode.

When a value of integer type is converted to a real floating type, if the value being converted can be represented exactly in the new type, it is unchanged. If the value being converted is in the range of values that can be represented but cannot be represented exactly, the result is either the nearest higher or nearest lower representable value, chosen in an implementation-defined manner. C17dr § 6.3.1.4 2

When the result it not exact, the converted value the nearest higher or nearest lower?
A round trip int --> float --> int is warranted.

Round tripping needs to watch out for convert(near_INT_MAX) converting to outside the int range.

Rather than rely on long or long long having a wider range than int (C does not specify this property), let code compare on the negative side as INT_MIN (with 2's complement) can be expected to convert exactly to a float.

float convert(int i) {
  int n = (i < 0) ? i : -i;  // n <= 0
  float f = (float) n;
  int rt_n = (int) f;  // Overflow not expected on the negative side
  // If f rounded away from 0.0 ...
  if (rt_n < n) {
    f = nextafterf(f, 0.0);  // Move toward 0.0
  }
  return (i < 0) f : -f;
}

Changing the rounding mode is somewhat expensive, although I think some modern x86 CPUs do rename MXCSR so it doesn't have to drain the out-of-order execution back-end.

If you care about performance, benchmarking njuffa's pure integer version (using shift = __builtin_clz(i); i<<=shift;) against the rounding-mode-changing version would make sense. (Make sure to test in the context you want to use it in; it's so small that it matters how well it overlaps with surrounding code.)

AVX-512 can use rounding-mode overrides on a per-instruction basis, letting you use a custom rounding mode for the conversion basically the same cost as a normal int->float. (Only available on Intel Skylake-server, and Ice Lake CPUs so far, unfortunately.)

#include <immintrin.h>

float int_to_float_trunc_avx512f(int a) {
  const __m128 zero = _mm_setzero_ps();      // SSE scalar int->float are badly designed to merge into another vector, instead of zero-extend.  Short-sighted Pentium-3 decision never changed for AVX or AVX512
  __m128 v = _mm_cvt_roundsi32_ss (zero, a, _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC);
  return _mm_cvtss_f32(v);               // the low element of a vector already is a scalar float so this is free.
}

_mm_cvt_roundi32_ss is a synonym, IDK why Intel defined both i and si names, or if some compilers might only have one.

This compiles efficiently with all 4 mainstream x86 compilers (GCC/clang/MSVC/ICC) on the Godbolt compiler explorer.

# gcc10.2 -O3 -march=skylake-avx512
int_to_float_trunc_avx512f:
        vxorps  xmm0, xmm0, xmm0
        vcvtsi2ss       xmm0, xmm0, {rz-sae}, edi
        ret

int_to_float_plain:
        vxorps  xmm0, xmm0, xmm0             # GCC is always cautious about false dependencies, spending an extra instruction to break it, like we did with setzero()
        vcvtsi2ss       xmm0, xmm0, edi
        ret

In a loop, the same zeroed register can be reused as a merge target, allowing the vxorps zeroing to be hoisted out of a loop.

Using _mm_undefined_ps() instead of _mm_setzero_ps(), we can get ICC to skip zeroing XMM0 before converting into it, like clang does for plain (float)i in this case. But ironically, clang which is normally cavalier and reckless about false dependencies compiles _mm_undefined_ps() the same as setzero in this case.

The performance in practice of vcvtsi2ss (scalar integer to scalar single-precision float) is the same whether you use a rounding-mode override or not (2 uops on Ice Lake, same latency: https://uops.info/). The AVX-512 EVEX encoding is 2 bytes longer than the AVX1.


Rounding mode overrides also suppress FP exceptions (like "inexact"), so you couldn't check the FP environment to later detect if the conversion happened to be exact (no rounding). But in this case, converting back to int and comparing would be fine. (You can do that without risk of overflow because of the rounding towards 0).

A simple solution is to use a higher precision floating point for comparison. As long as the high precision floating point can exactly represent all integers, we can accurately compare whether the float result was greater.

double should be sufficient with 32 bit integers, and long double is sufficient for 64 bit on most systems, but it's good practice to verify it.

float convert(int x) {
    static_assert(std::numeric_limits<double>::digits
                  >= sizeof(int) * CHAR_BIT);
    float  f = x;
    double d = x;
    return std::abs(f) > std::abs(d)
        ? std::nextafter(f, 0.f)
        : f;
}
  1. Shift the integer right by an arithmetic shift until the number of bits agrees with the precision of the floating point arithmetic. Count the shifts.
  2. Convert the integer to float. The result is now precise.
  3. Multiply the resulting float by a power of two corresponding to the number of shifts.

For nonnegative values, this can be done by taking the integer value and shifting right until the highest set bit is less than 24 bits (i.e. the precision of IEEE single) from the right, then shifting back.

For negative values, you would shift right until all bits from 24 and up are set, then shift back. For the shift back, you'll first need to cast the value to unsigned to avoid undefined behavior of left-shifting a negative value, then cast the result back to int before converting to float.

Note also that the conversion from unsigned to signed is implementation defined, however we're already dealing with ID as we're assuming float is IEEE754 and int is two's complement.

float rount_to_zero(int x)
{
    int cnt = 0;
    if (x >= 0) {
        while (x != (x & 0xffffff)) {
            x >>= 1;
            cnt++;
        }
        return x << cnt;
    } else {
        while (~0xffffff != (x & ~0xffffff)) {
            x >>= 1;
            cnt++;
        }
        return (int)((unsigned)x << cnt);
    }
}
Related