Avoid undefined behaviour with float to integer conversion

When converting a value of floating type to an integer type, and the
result is outside of the range of the integer type the result is
undefined.  Avoid this by clamping the value to the range of the target
type.