1 unstable release
| 0.1.0 | Dec 20, 2025 |
|---|
#1216 in Algorithms
Used in nvana_rev_epoch
52KB
728 lines
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:
[dependencies]
nvana_fixed = "0.1.0"
Quick Start
use nvana_fixed::PreciseNumber;
// Basic arithmetic
let a = PreciseNumber::new(10).unwrap();
let b = PreciseNumber::new(3).unwrap();
let sum = a.checked_add(&b).unwrap();
let product = a.checked_mul(&b).unwrap();
let quotient = a.checked_div(&b).unwrap();
assert_eq!(sum.to_imprecise().unwrap(), 13);
assert_eq!(product.to_imprecise().unwrap(), 30);
assert_eq!(quotient.to_imprecise().unwrap(), 3); // Rounded
// Working with percentages
let rate = PreciseNumber::from_basis_points(500).unwrap(); // 5%
let principal = PreciseNumber::new(1000).unwrap();
let interest = principal.checked_mul(&rate).unwrap();
assert_eq!(interest.to_imprecise().unwrap(), 50);
// Comparisons
assert!(a < b.checked_mul(&PreciseNumber::new(2).unwrap()).unwrap());
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.
Dependencies
~250KB