finanza/decimal
Fixed-point decimal numbers with explicit rounding.
A Decimal is a coefficient and a base-10 exponent, so 12.30 is
the coefficient 1230 with the exponent -2. Operations that can
lose digits take a RoundingMode.
Range
Every Decimal is in this range, on both targets:
- The exponent is between -28 and 15, so a decimal has at most 28
places after the point. Currencies use 0 to 4 places and interest
rates rarely need more than 10, and 28 is the largest scale of
rust_decimal and .NET
System.Decimal. 15 is the largest exponent at which a non-zero coefficient fits the bound below. - The coefficient, and the integer a positive exponent stands for, are within ±9,007,199,254,740,991 (2^53 − 1), the largest integer JavaScript represents exactly, so Erlang and JavaScript give the same results.
Together these keep to_string at 31 characters or fewer, so a short
input such as "1e-999999999" cannot become a long string.
new returns Error(Nil) outside the range, parse returns
ParsedValueTooLarge, and arithmetic returns PrecisionExceeded,
also when round or divide is asked for more than 28 places.
parse rejects input over 1,000 bytes with InputTooLong before
reading it, the same limit as the default number length of Jackson’s
StreamReadConstraints.
Types
Why an arithmetic operation failed.
pub type ArithmeticError {
DivisionByZero
PrecisionExceeded
}
Constructors
-
DivisionByZeroThe divisor was zero.
-
PrecisionExceededThe result does not fit in the supported range.
Why parse rejected its input.
pub type ParseError {
EmptyInput
InvalidCharacter(character: String, position: Int)
MultipleDecimalPoints
MultipleSigns
NoDigits
ParsedValueTooLarge
InputTooLong
}
Constructors
-
EmptyInputThe input was empty or only whitespace.
-
InvalidCharacter(character: String, position: Int)The input has a character that is not a digit, a sign, a
.or an exponent marker.positioncounts graphemes from 0 after the surrounding whitespace is trimmed. -
MultipleDecimalPointsThe input has more than one
.. -
MultipleSignsThe input has more than one sign, or a sign after the first character.
-
NoDigitsThe input has no digits, such as
"+"or".". -
ParsedValueTooLargeThe value is outside the supported range: more than 2^53 − 1 in the coefficient, or an exponent outside -28 to 15, even after the trailing zeros are dropped, as for
"1e-29"or"1e16". -
InputTooLongThe input is longer than 1,000 bytes, counted before trimming.
How to round when an operation drops digits.
HalfEven (banker’s rounding) is the usual choice for money.
pub type RoundingMode {
HalfEven
HalfUp
HalfDown
Up
Down
Ceiling
Floor
}
Constructors
-
HalfEvenRound half-way values to the even neighbour: 2.5 to 2, 3.5 to 4.
-
HalfUpRound half-way values away from zero: 2.5 to 3, -2.5 to -3.
-
HalfDownRound half-way values toward zero: 2.5 to 2, -2.5 to -2.
-
UpRound away from zero: 2.1 to 3, -2.1 to -3.
-
DownRound toward zero: 2.9 to 2, -2.9 to -2.
-
CeilingRound toward positive infinity: 2.1 to 3, -2.9 to -2.
-
FloorRound toward negative infinity: 2.9 to 2, -2.1 to -3.
Values
pub fn add(
a: Decimal,
b: Decimal,
) -> Result(Decimal, ArithmeticError)
Adds two decimals without rounding.
The sum is exact before it is fitted into the range, even when one
operand scaled to the other’s exponent passes 2^53 − 1. It has the
smaller of the two exponents when its coefficient fits there, as in
Python’s decimal, so 1 + -0.8999999999999999 is
0.1000000000000001 and 0.00 + 5 is 5.00. Otherwise it drops
the fewest trailing zeros that bring the coefficient within
2^53 − 1, so 1 + 0.1000000000000000 is 1.100000000000000, with
the exponent -15.
Returns Error(PrecisionExceeded) when the sum is out of range,
including one that needs more than 2^53 − 1 in its coefficient after
its zeros go, such as 1e15 + 1e-28.
pub fn coefficient(decimal: Decimal) -> Int
Returns the coefficient, so 12.30 gives 1230.
pub fn compare(a: Decimal, b: Decimal) -> order.Order
Compares two decimals by value, so 1.0 and 1.00 are equal.
pub fn divide(
a: Decimal,
b: Decimal,
digits digits: Int,
rounding mode: RoundingMode,
) -> Result(Decimal, ArithmeticError)
Divides a by b and rounds the quotient to digits places after
the decimal point.
Returns Error(DivisionByZero) when b is zero, and
Error(PrecisionExceeded) when digits is outside -15 to 28 or the
quotient at that many places is out of range, which happens from
17 places for 1 / 3. The quotient is exact before rounding
even when the scaled dividend would pass 2^53, so
1 / 1.234567890123456 at 2 places is 0.81.
Examples
let assert Ok(ten) = decimal.from_int(10)
let assert Ok(three) = decimal.from_int(3)
decimal.divide(ten, three, digits: 2, rounding: decimal.HalfEven)
|> result.map(decimal.to_string)
// -> Ok("3.33")
pub fn equal(a: Decimal, b: Decimal) -> Bool
Returns True when two decimals have the same value. == compares
the representation instead, so 1.0 == 1.00 is False but
equal(1.0, 1.00) is True.
pub fn exponent(decimal: Decimal) -> Int
Returns the base-10 exponent, so 12.30 gives -2.
pub fn format(
decimal: Decimal,
thousands thousands: String,
decimal_separator decimal_separator: String,
) -> String
Renders the decimal like to_string, with thousands between
groups of three integer digits and decimal_separator in place of
the ..
Examples
let assert Ok(price) = decimal.parse("1234567.5")
decimal.format(price, thousands: ".", decimal_separator: ",")
// -> "1.234.567,5"
pub fn from_float(value: Float) -> Result(Decimal, ParseError)
Creates a decimal from the text float.to_string gives for a float.
0.5 becomes 0.5, and 0.1 +. 0.2 becomes
0.30000000000000004. Prefer parse or new when the value is
not already a float.
pub fn from_int(value: Int) -> Result(Decimal, Nil)
Creates a decimal from an integer.
Returns Error(Nil) when the integer is outside
±9,007,199,254,740,991.
pub fn is_negative(decimal: Decimal) -> Bool
Returns True when the decimal is less than zero.
pub fn is_positive(decimal: Decimal) -> Bool
Returns True when the decimal is greater than zero.
pub fn multiply(
a: Decimal,
b: Decimal,
) -> Result(Decimal, ArithmeticError)
Multiplies two decimals without rounding. The exponents add up, so
1.5 × 0.25 is 0.375.
The product is exact before it is fitted into the range, even when
the coefficients multiply past 2^53. When the exponents add up to
less than -28, or the coefficient passes 2^53 − 1, the product drops
the fewest trailing zeros that bring it into range, so 0.10 × 1e-27
is 1e-28 and 4503599627370496 × 0.10 is 450359962737049.6. A
zero product has its exponent moved into -28 to 15.
Returns Error(PrecisionExceeded) when the product is out of range,
including a product with a non-zero digit past 28 places, such as
1000.01 × 1e-27, or one that needs more than 2^53 − 1 in its
coefficient after its zeros go. multiply never rounds; to round a
product, money.multiply rounds to a currency’s minor unit.
pub fn new(
coefficient coefficient: Int,
exponent exponent: Int,
) -> Result(Decimal, Nil)
Creates the decimal coefficient × 10^exponent.
Returns Error(Nil) when the value is outside the supported range:
the exponent must be between -28 and 15, and the coefficient, times
10^exponent when the exponent is positive, within ±(2^53 − 1).
Examples
decimal.new(coefficient: 1234, exponent: -2) |> result.map(decimal.to_string)
// -> Ok("12.34")
decimal.new(coefficient: 1, exponent: 16)
// -> Error(Nil)
pub fn parse(input: String) -> Result(Decimal, ParseError)
Parses a decimal such as "12.30", "-0.5", "+7" or "1.5e-3".
Leading and trailing Unicode whitespace is ignored, including
no-break spaces. The exponent is kept as written when it is in range,
so "12.30" and "12.3" parse to different representations of the
same number. When it is not, the fewest trailing zeros that bring the
value into range are dropped, the same rule as add and multiply
follow: "0.10000000000000000000000000000" (29 places) is
0.1000000000000000 and "9007199254740991.0" is
9007199254740991. A zero gets its exponent moved into -28 to 15.
Returns Error(InputTooLong) for input over 1,000 bytes and
Error(ParsedValueTooLarge) for a value outside the range in the
module documentation, such as "1e-29" or "1e16".
Examples
decimal.parse(" 12.30 ") |> result.map(decimal.to_string)
// -> Ok("12.30")
decimal.parse("1.2.3")
// -> Error(decimal.MultipleDecimalPoints)
pub fn round(
decimal: Decimal,
digits digits: Int,
rounding mode: RoundingMode,
) -> Result(Decimal, ArithmeticError)
Rounds the decimal to digits places after the decimal point.
The result always has exactly digits places: 12.3 rounded to 2
places is 12.30. A negative digits rounds to tens, hundreds and
so on. Returns Error(PrecisionExceeded) when digits is outside
-15 to 28 or the padded or rounded value is out of range.
Examples
let assert Ok(price) = decimal.parse("2.345")
decimal.round(price, digits: 2, rounding: decimal.HalfEven)
|> result.map(decimal.to_string)
// -> Ok("2.34")
let assert Ok(price) = decimal.parse("2.345")
decimal.round(price, digits: 2, rounding: decimal.HalfUp)
|> result.map(decimal.to_string)
// -> Ok("2.35")
pub fn subtract(
a: Decimal,
b: Decimal,
) -> Result(Decimal, ArithmeticError)
Subtracts b from a without rounding, the same as adding
negate(b).
pub fn to_int(decimal: Decimal) -> Result(Int, Nil)
Converts a whole-number decimal to an Int.
Returns Error(Nil) when the decimal has a non-zero fractional
part. Use round with digits: 0 first to drop it.
Examples
decimal.parse("12.00") |> result.try(decimal.to_int)
// -> Ok(12)
decimal.parse("12.34") |> result.try(decimal.to_int)
// -> Error(Nil)
pub fn to_string(decimal: Decimal) -> String
Renders the decimal with every digit of its exponent, so
new(coefficient: 100, exponent: -2) is "1.00" and
new(coefficient: 12, exponent: 2) is "1200".