nvana_fixed
A high-precision fixed-point arithmetic library for Rust, designed for financial and DeFi calculations where precision is critical.
Features
- High Precision: 18 decimal places of precision (WAD format)
- Large Range: Uses U256 internally, supporting values much larger than u128
- Safe Arithmetic: All operations are checked and return
Optionon overflow/underflow - DeFi Ready: Built-in support for basis points and micro basis points
- Comparison Traits: Full support for equality and ordering operations
Installation
Add this to your Cargo.toml:
[]
= "0.1.0"
Quick Start
use PreciseNumber;
// Basic arithmetic
let a = new.unwrap;
let b = new.unwrap;
let sum = a.checked_add.unwrap;
let product = a.checked_mul.unwrap;
let quotient = a.checked_div.unwrap;
assert_eq!;
assert_eq!;
assert_eq!; // Rounded
// Working with percentages
let rate = from_basis_points.unwrap; // 5%
let principal = new.unwrap;
let interest = principal.checked_mul.unwrap;
assert_eq!;
// Comparisons
assert!;
How It Works
PreciseNumber uses a fixed-point representation with 18 decimal places. Internally, values are stored as value * 10^18 in a 256-bit integer:
1.0is stored as1_000_000_000_000_000_0000.5is stored as500_000_000_000_000_00042.123is stored as42_123_000_000_000_000_000
All arithmetic operations include automatic rounding correction to minimize truncation errors.
Safety
All arithmetic operations return Option<PreciseNumber> and will return None on:
- Overflow
- Underflow
- Division by zero
This ensures your code can handle edge cases gracefully.
License
Licensed under MIT.