nvana_fixed 0.1.0

High-precision fixed-point arithmetic library for financial and DeFi calculations
Documentation
  • Coverage
  • 100%
    21 out of 21 items documented16 out of 16 items with examples
  • Size
  • Source code size: 52.45 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 2.54 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 16s Average build duration of successful builds.
  • all releases: 16s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • nirvana-sid

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 Option on 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.0 is stored as 1_000_000_000_000_000_000
  • 0.5 is stored as 500_000_000_000_000_000
  • 42.123 is stored as 42_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.