Skip to content

decimal — точные числа для денег ​

mzs
include decimal

INFO

Доступен в скриптах ботов.

float двоичный: 0.1 + 0.2 — это 0.30000000000000004. Десятичное число хранит цифры как написано.

ФункцияЧто делает
decimal.of(x)строка или int → десятичное; float — ошибка
decimal.plus(a, b, …)сумма
decimal.minus(a, b)разность
decimal.times(a, b, …)произведение
decimal.div(a, b)частное, только точное — иначе ошибка
decimal.div(a, b, places, mode)частное, округлённое до places знаков
decimal.neg(a), decimal.abs(a)минус, модуль
decimal.cmp(a, b)-1, 0 или 1
decimal.round(a, places, mode)округлить; mode — "half_up" (по умолчанию) или "half_even"
decimal.str(a), decimal.str(a, places)в строку; с places — ровно столько знаков
decimal.float(a), decimal.int(a)в float (с потерей), в int (отбросить дробь)
decimal.sum(xs)сумма массива
decimal.split(a, ways, places)разделить на ways частей без потери копейки

Все функции, кроме of, принимают и int.

Посчитать ​

mzs
include decimal
price = decimal.of("1500.35")
vat = decimal.times(price, decimal.of("0.20"))
decimal.str(decimal.plus(price, vat), 2)  # → "1800.42"
decimal.str(decimal.times(decimal.of("1.05"), 3))  # → "3.15"
decimal.str(decimal.minus(decimal.of("1"), decimal.of("0.01")))  # → "0.99"
decimal.plus(decimal.of("0.1"), decimal.of("0.2")) == decimal.of("0.3")  # → true

Сумма корзины:

mzs
include decimal
cart = [{price: "199.90", qty: 2}, {price: "49.99", qty: 1}]
total = decimal.sum(cart.map { decimal.times(decimal.of(it["price"]), it["qty"]) })
decimal.str(total, 2)  # → "449.79"

Делить и округлять ​

mzs
include decimal
decimal.str(decimal.div(decimal.of(10), decimal.of(4)))  # → "2.5"
decimal.str(decimal.div(decimal.of(1), decimal.of(3), 4))  # → "0.3333"
decimal.str(decimal.round(decimal.of("2.665"), 2))  # → "2.67"
decimal.str(decimal.round(decimal.of("2.665"), 2, "half_even"))  # → "2.66"
decimal.str(decimal.round(decimal.of("1250"), -2))  # → "1300"
decimal.str(decimal.of("1.5"), 2)  # → "1.50"

1 / 3 без places — ошибка: точного ответа нет.

mzs
include decimal
decimal.div(decimal.of(1), decimal.of(3))
text
has no exact decimal form within 18 places

Разделить сумму ​

Остаток уходит первым частям, сумма частей равна целому.

mzs
include decimal
parts = decimal.split(decimal.of("10"), 3, 2)
parts.map { decimal.str(it, 2) }  # → ["3.34","3.33","3.33"]
decimal.str(decimal.sum(parts), 2)  # → "10.00"

Сравнить и отсортировать ​

mzs
include decimal
decimal.cmp(decimal.of("9"), decimal.of("10"))  # → -1
decimal.of("1.50") == decimal.of("1.5")  # → true
["9.5", "10", "0.75"].map { decimal.of(it) }.sort { (a, b) -> decimal.cmp(a, b) }.map { decimal.str(it) }  # → ["0.75","9.5","10"]

< и + между десятичными — ошибка: это словари. Используйте cmp и plus.

mzs
include decimal
decimal.of("1.5") + decimal.of("2")
text
cannot add Decimal to Decimal

Что внутри ​

Десятичное — словарь {units, scale}: значение units × 10^-scale. Так оно и пишется в JSON и читается обратно.

mzs
include decimal
decimal.of("1500.35")  # → {"units":150035,"scale":2}
type(decimal.of("1.5"))  # → "Decimal"
decimal.str(decimal.of({units: 150035, scale: 2}), 2)  # → "1500.35"

В JSON для людей пишите строку: {total: decimal.str(d, 2)}.json.

Ошибки ​

mzs
include decimal
try decimal.of("1 500,35") else (e) -> e["kind"]  # → "decimal"
try decimal.of(1500.35) else (e) -> e["kind"]  # → "type"
try decimal.div(decimal.of(1), 0) else (e) -> e["kind"]  # → "zero-division"

of читает только цифры, точку и знак: без пробелов-разделителей, запятой и экспоненты. Больше 18 знаков после точки — ошибка.