# \[dry-types\] Coercing String with decimal to Integer fails

**URL:** <https://discourse.dry-rb.org/t/dry-types-coercing-string-with-decimal-to-integer-fails/1541>\
**Category:** dry-types\
**Created:** [October 28, 2022, 10:05pm UTC](https://discourse.dry-rb.org/t/dry-types-coercing-string-with-decimal-to-integer-fails/1541 "2022-10-28T22:05:15Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![aqlien](https://yyz1.discourse-cdn.com/flex031/user_avatar/discourse.dry-rb.org/aqlien/32/810_2.png) [@aqlien](https://discourse.dry-rb.org/u/aqlien)\
**Post date:** [October 28, 2022, 10:05pm UTC](https://discourse.dry-rb.org/t/dry-types-coercing-string-with-decimal-to-integer-fails/1541/1 "2022-10-28T22:05:15Z")

</div>

Using Types::Params::Integer to convert a String containing a number with a decimal point results in an error.  
`Dry::Types::Coercions::Params.to_int("1.5")` = `invalid value for Integer(): "1.5" (Dry::Types::CoercionError)`

I assumed the converter would act identically to Ruby’s String#to\_i and remove any digits after the decimal point.  
`"1.5".to_i` = `1`

Right now I’m adding a check before performing a call using Types::Params::Integer. If the value is a String, I use .to\_i instead. But that feels like terrible hack. Can anyone suggest a better way?

---

<div class="post-metadata">

**Author:** ![solnic](https://yyz1.discourse-cdn.com/flex031/user_avatar/discourse.dry-rb.org/solnic/32/779_2.png) [@solnic](https://discourse.dry-rb.org/u/solnic)\
**Post date:** [October 30, 2022, 7:11am UTC](https://discourse.dry-rb.org/t/dry-types-coercing-string-with-decimal-to-integer-fails/1541/2 "2022-10-30T07:11:41Z")

</div>

> [@aqlien](#):
>
> I assumed the converter would act identically to Ruby’s String#to\_i and remove any digits after the decimal point.

It’s purposefully not acting as the built-in coercion as it’s not strict enough. You can define your own coercion like this:

```ruby
irb(main):005:0> MyInt = Types.Constructor(Integer, &:to_i)
=> #<Dry::Types[Constructor<Nominal<Integer> fn=.to_i>]>
irb(main):006:0> MyInt["1.5"]
=> 1

```

However, notice that this may lead to all kinds of weird behavior, like this:

```ruby
irb(main):008:0> MyInt["afa1.5afa"]
=> 0

```

This is why params coercions are much more strict about the input.

---

<div class="post-metadata">

**Author:** ![aqlien](https://yyz1.discourse-cdn.com/flex031/user_avatar/discourse.dry-rb.org/aqlien/32/810_2.png) [@aqlien](https://discourse.dry-rb.org/u/aqlien)\
**Post date:** [October 31, 2022, 8:47pm UTC](https://discourse.dry-rb.org/t/dry-types-coercing-string-with-decimal-to-integer-fails/1541/3 "2022-10-31T20:47:46Z")

</div>

Ah, got it, that makes sense. Thank you for letting me know the right way to define my own coercion.
