Ecto string/float conversion

I’m trying to do something pretty simple, and I’m wondering if there’s an obvious easy way I’m missing. I have a float-as-string in memory. I want to persist it as a float, but cast it to/from a string when it’s saved and loaded. I know I can use an Ecto custom type. Is there a more terse way anyone can point me to? This seems like a typical thing that is probably done all the time.

1 Like

I’m not thats a common requirement (maybe just me - i;ve never had a use case for that). I think a custom type is the right way to do it if thats your requirement though. Everything else leaves room for error or forgetfulness.

You can use some Postgres type-casting on the way in from the database with a fragment:

from p in Post,
  select:  fragment("?::text", p.float_thing)

But whilst terse its hackish for sure.

1 Like

Or you can make an Ecto ‘Type’ (see the docs, it’s easy, you just define a module with a couple functions and use that module name as the type). :slight_smile:

1 Like