How to set default decimal precision?

Noob question, how do I set the default decimal precision in phoenix?

I can see from the Decimal docs I need to run D.Context.set(%D.Context{D.Context.get() | precision: 48}) but where do I set this so when I run mix phx.server or iex -S mix it’s already set?

You could add it to the start/2 function of your Application module. For example:

defmodule MyApp.Applications do
  def start(_type, args) do
    D.Context.set(%D.Context{D.Context.get() | precision: 48})

    children = [

    supervisor = Supervisor.start_link(children, args)

Decimal.Context.get/set are a trivial wrapper over an entry in the process dictionary:

so AFAIK there’s not a “global” place to change them.


Unfortunately this doesn’t seem to work. @al2o3cr might be right and there might not be a global place to set it :face_with_monocle:

There is no global place to set it, it needs to be set in each process where you want it to be in affect. So if you’re talking about a Phoenix app (which you are I see from above), then you’ll need to set it in each request (as a plug would make sense). And then in each other process like liveview processes.


The flipside of setting the context being really cheap: it’s fine to do it frequently, close to the code that depends on specific settings.

Setting it close to the calculation also avoids gotchas where code runs in another process unexpectedly; for instance, Cachex.fetch runs the supplied fallback function in an internal process, NOT the caller’s process.