# Clamp floats to int

**URL:** <https://discourse.julialang.org/t/clamp-floats-to-int/52624>\
**Category:** New to Julia\
**Created:** [December 30, 2020, 5:45pm UTC](https://discourse.julialang.org/t/clamp-floats-to-int/52624 "2020-12-30T17:45:56Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![hergum](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/hergum/32/20667_2.png) [@hergum](https://discourse.julialang.org/u/hergum)\
**Post date:** [December 30, 2020, 5:45pm UTC](https://discourse.julialang.org/t/clamp-floats-to-int/52624/1 "2020-12-30T17:45:56Z")

</div>

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))

---

<div class="post-metadata">

**Author:** ![Oscar\_Smith](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oscar_smith/32/25343_2.png) [@Oscar\_Smith](https://discourse.julialang.org/u/Oscar_Smith)\
**Post date:** [December 30, 2020, 5:58pm UTC](https://discourse.julialang.org/t/clamp-floats-to-int/52624/2 "2020-12-30T17:58:49Z")

</div>

`round(UInt8, -1.1)`

---

<div class="post-metadata">

**Author:** ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)\
**Post date:** [December 30, 2020, 6:19pm UTC](https://discourse.julialang.org/t/clamp-floats-to-int/52624/3 "2020-12-30T18:19:12Z")

</div>

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`.

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [December 30, 2020, 6:27pm UTC](https://discourse.julialang.org/t/clamp-floats-to-int/52624/4 "2020-12-30T18:27:12Z")

</div>

you can combine `clamp` and `unsafe_trunc`:

```julia
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)

---

<div class="post-metadata">

**Author:** ![hergum](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/hergum/32/20667_2.png) [@hergum](https://discourse.julialang.org/u/hergum)\
**Post date:** [December 30, 2020, 6:55pm UTC](https://discourse.julialang.org/t/clamp-floats-to-int/52624/5 "2020-12-30T18:55:59Z")

</div>

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