lue-bird / elm-morph / Decimal

Arbitrary-size, safe floating point number with the explicit option of allowing of exceptions or not. See also Decimal.Morph


type Decimal
    = N0
    | Signed Signed

A decimal number that can have a floating point

Don't shy away from spinning your own version of this if needed, like

type FieldException
    = DivisionByZeroResult
    | Infinity Sign

Result FieldException Decimal

See also Decimal.Exception


type alias Signed =
RecordWithoutConstructorFunction { sign : Sign
, absolute : SignedAbsolute 
}

Any Decimal except 0 is represented this way


type SignedAbsolute
    = Fraction Fraction
    | AtLeast1 AtLeast1

What comes after its Sign


type alias Fraction =
RecordWithoutConstructorFunction { beforeEnd : List (N (N.In N0 N9))
, end : N (N.In N1 N9) 
}

Some digits after the decimal point. Can't be none.

Note that "fraction" here doesn't mean "rational number with a numerator and denominator" or "number in range [0;1]" It means: the absolute value of a written decimal number without a period, like 0.345 or 0.001

You think this name can be improved? → issue


type alias AtLeast1 =
RecordWithoutConstructorFunction { whole : Natural.AtLeast1
, fraction : Maybe Fraction 
}

Absolute value of a signed Decimal ≥ 1


type Exception
    = NaN
    | Infinity Sign

Non-number calculation result, see also IEEE 754 number exception states

Result Exception Decimal for example is like an elm/core Float except

create

fromFloat : Basics.Float -> Result Exception Decimal

Convert from an elm/core Float. Don't be surprised to find more precise representations in Decimal-land

-9999.124 |> Decimal.fromFloat
--→ Ok with the Decimal representation of
--→ 999.1239999999997962731868028640747070312

alter

ceiling : Decimal -> Integer

Its nearest greater Integer number

floor : Decimal -> Integer

Its nearest lower Integer number

truncate : Decimal -> Integer

Remove the Fraction part after the decimal point . to create an Integer

transform

toFloat : Decimal -> Basics.Float

Convert to a Float

Keep in mind that DecimalOrException -> Float can be lossy since Float is fixed in bit size while Decimal is not

orExceptionToFloat : Result Exception Decimal -> Basics.Float

NaN, infinity or Decimal.toFloat

Keep in mind that Decimal -> Float can be lossy since Float is fixed in bit size while Decimal is not

exceptionToFloat : Exception -> Basics.Float

infinity/NaN represented as a Float