Bylaw.Credo.Check.Elixir.FloatUsage (bylaw_credo v0.1.0-alpha.1)

Copy Markdown View Source

Basics

This check is disabled by default.

Learn how to enable it via .credo.exs.

This check has a base priority of high and works with any version of Elixir.

Explanation

Prefer Decimal over floats in Ecto migrations, Ecto schemas, and Elixir code.

Floats are approximate binary numbers. Many decimal values cannot be represented exactly as floats, which can make calculations, rounding, equality checks, and persisted values surprising for money, tax, rates, balances, quantities, and other business data.

For example, a float calculation may keep a tiny representation error:

  0.1 + 0.2

Use the Decimal library and Ecto's :decimal type when a value needs decimal precision or predictable rounding:

  Decimal.add(Decimal.new("0.1"), Decimal.new("0.2"))

Floats may still be appropriate for approximate measurements, statistics, scientific calculations, graphics, telemetry, or other domains where small precision differences are expected and acceptable.

Examples

Avoid:

  add :amount, :float
  field :amount, :float
  Float.round(value, 2)
  amount = 1.25
  @spec amount() :: float()

Prefer:

  add :amount, :decimal
  field :amount, :decimal
  Decimal.round(value, 2)
  amount = Decimal.new("1.25")
  @spec amount() :: Decimal.t()

If a float is genuinely required, document the exception and disable the check locally.

Notes

This check uses static AST analysis, so it favors clear source-level patterns over runtime behavior.

Options

This check has no check-specific options. Configure it with an empty option list.

Usage

Add this check to Credo's checks: list in .credo.exs:

%{
  configs: [
    %{
      name: "default",
      checks: [
        {Bylaw.Credo.Check.Elixir.FloatUsage, []}
      ]
    }
  ]
}

Check-Specific Parameters

There are no specific parameters for this check.

General Parameters

Like with all checks, general params can be applied.

Parameters can be configured via the .credo.exs config file.