Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

rust-decimal

БесплатноБез исполняемых скриптовНе проверен

rust_decimal — fixed-point decimal arithmetic for Rust. 128-bit signed decimal, exact (no float rounding errors), suitable for finance, currency, Bitcoin sat…

claude-dev-suiteот claude-dev-suite★ 51 звезда на GitHub

Об этом скилле

rust_decimal — Exact Decimal Arithmetic

Deep Knowledge: Use mcp__documentation__fetch_docs with technology: rust-decimal.

Why Not f64 for Money

let total: f64 = 0.1 + 0.2;
println!("{}", total);                            // 0.30000000000000004 — WRONG

let cents: f64 = 100.50_f64;
let cents_int = (cents * 100.0) as i64;
println!("{}", cents_int);                        // 10049 — WRONG (should be 10050)

Floating-point cannot represent most decimal fractions exactly. For money, this is unacceptable: rounding bugs become real losses, audit failures, regulatory issues.

For Bitcoin specifically: always use i64 for sats (1 BTC = 100,000,000 sats fits easily). For fiat conversions, multi-currency display, fee calculations involving rates → use Decimal.

Setup

[dependencies]
rust_decimal = "1.36"
rust_decimal_macros = "1.36"

# Optional features
rust_decimal = { version = "1.36", features = ["serde-with-str", "db-postgres", "macros"] }

Useful features:

  • serde-with-str — serialize as string (preserves precision in JSON)
  • serde-with-float — serialize as float (loses precision, but compatible)
  • serde-with-arbitrary-precision — preserve via serde_json's arbitrary precision
  • db-postgres, db-tokio-postgres, db-diesel — DB integration
  • macros — dec! literal macro
  • maths — extra math functions (exp, ln, sin, etc.)
  • tokio-pg — async postgres
  • borsh — binary serialization for blockchain projects

Basic Usage

use rust_decimal::Decimal;
use rust_decimal_macros::dec;

let a = dec!(0.1);
let b = dec!(0.2);
let c = a + b;
assert_eq!(c, dec!(0.3));                         // EXACT

let price = dec!(19.99);
let quantity = dec!(3);
let total = price * quantity;
assert_eq!(total, dec!(59.97));

// Division
let avg = total / quantity;
assert_eq!(avg, dec!(19.99));

dec! macro creates Decimal at compile time, validates literal.

From Strings

use std::str::FromStr;

let amount = Decimal::from_str("0.00012345")?;
let amount: Decimal = "12345.6789".parse()?;

For untrusted input always parse — never as from float.

From Integers

let sats = Decimal::from(100_000_000_i64);
let btc = sats / dec!(100_000_000);
assert_eq!(btc, dec!(1));

To Various Types

let d = dec!(123.456);

let s: String = d.to_string();                     // "123.456"
let f: f64 = d.try_into()?;                        // 123.456 (lossy)
let i: i64 = d.try_into()?;                        // ERROR — has fractional part
let i: i64 = (d * dec!(1_000)).round().try_into()?; // 123456 (scaled)

Bitcoin sats ↔ fiat Conversion

use rust_decimal::Decimal;
use rust_decimal_macros::dec;

const SATS_PER_BTC: i64 = 100_000_000;

fn sats_to_fiat(sats: i64, btc_to_fiat_rate: Decimal) -> Decimal {
    let btc = Decimal::from(sats) / Decimal::from(SATS_PER_BTC);
    btc * btc_to_fiat_rate
}

fn fiat_to_sats(fiat: Decimal, btc_to_fiat_rate: Decimal) -> i64 {
    let btc = fiat / btc_to_fiat_rate;
    let sats = btc * Decimal::from(SATS_PER_BTC);
    sats.round().to_i64().unwrap_or(0)
}

// Example: at $60,000/BTC
let rate = dec!(60000);
let sats = 100_000;                                // 0.001 BTC
let usd = sats_to_fiat(sats, rate);
assert_eq!(usd, dec!(60.00));

let euro_amount = dec!(100);
let euro_rate = dec!(55000);                       // €55,000/BTC
let needed_sats = fiat_to_sats(euro_amount, euro_rate);
assert_eq!(needed_sats, 181_818);                  // sats

Rounding

use rust_decimal::RoundingStrategy;

let d = dec!(2.5);

let rounded = d.round();                                          // banker's rounding by default → 2
let rounded_half_up = d.round_dp_with_strategy(0, RoundingStrategy::MidpointAwayFromZero);  // 3
let truncated = d.round_dp_with_strategy(0, RoundingStrategy::ToZero);  // 2

// Specific decimal places
let price = dec!(19.9999);
let display_2dp = price.round_dp(2);                              // 20.00
let display_4dp = price.round_dp(4);                              // 19.9999

RoundingStrategy variants:

  • MidpointAwayFromZero — "round half up" (most intuitive)
  • MidpointTowardZero — "round half down"
  • MidpointNearestEven — banker's rounding (default for round())
  • ToZero — truncate
  • AwayFromZero — always round away from zero
  • ToNegativeInfinity — floor
  • ToPositiveInfinity — ceiling

For fiat display: typically MidpointAwayFromZero to 2 decimal places.

For Bitcoin fee calculations: use ToPositiveInfinity (always pay enough fee).

Comparison

let a = dec!(1.0);
let b = dec!(1.00);

assert_eq!(a, b);                                  // ✅ equal in value
assert_eq!(a.scale(), 1);                          // a has scale 1
assert_eq!(b.scale(), 2);                          // b has scale 2

// Hash works correctly even with different scales
use std::collections::HashSet;
let mut set = HashSet::new();
set.insert(a);
assert!(set.contains(
Полный SKILL.md на GitHub

Установить rust-decimal в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Read
Grep
Glob
Write
Edit

FAQ

Что делает скилл rust-decimal?

rust_decimal — fixed-point decimal arithmetic for Rust. 128-bit signed decimal, exact (no float rounding errors), suitable for finance, currency, Bitcoin sat ↔ fiat conversions, accounting. Up to 28 significant digits, arithmetic preserves precision. Includes RoundingStrategy for explicit truncation/rounding control. Integrates with serde, sqlx, postgres. USE WHEN: user mentions "rust_decimal", "Decimal", "dec!", "RoundingStrategy", "no float", "exact arithmetic", "fixed-point Rust", "currency math Rust", "sat to fiat conversion" DO NOT USE FOR: Crypto primitives - use `security/libsodium` or `bitcoin/cryptography/*` DO NOT USE FOR: BigInteger / arbitrary-precision math - use `num-bigint` DO NOT USE FOR: Time/duration math - use `chrono` or `time` crate

Как установить скилл rust-decimal?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл rust-decimal запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить rust-decimal с