Clamp floats to int

What is the appropriate way to clamp/convert a vector of floats to (unsigned) integers? I dont want convert/clamp/round/UInt8 to error out with InexactError, I just want to force some float’s into UInt8’s.

I am sure there is a builtin somewhere to avoid UInt8(min(typemax(UInt8),max(typemin(UInt8),-1.1))

round(UInt8, -1.1)

1 Like

Note that round will throuw an InexactError if the value is too large to be represented. I’m not aware of a built-in function, but you may simplify it slightly by using clamp instead of min,max.

1 Like

you can combine clamp and unsafe_trunc:

clamp_to(T, x) = unsafe_trunc(T, clamp(x, typemin(T), typemax(T)))

(Base.trunc checks the min(T) <= x <= max(T) then decide if error or call unsafe_trunc)

3 Likes

Thanks! Seems there is no built-in for this, your solution works fine.

1 Like