This crate strives to provide a fast implementation of Decimal fixed-point
arithmetics.
It is targeted at typical business applications, dealing with numbers representing quantities, money and the like, not at scientific computations, for which the accuracy of floating point math is - in most cases - sufficient.
Objectives
- "Exact" representation of decimal numbers (no deviation as with binary floating point numbers)
- No hidden rounding errors (as inherent to floating point math)
- Very fast operations (by mapping them to integer ops)
- Range of representable decimal numbers sufficient for typical business applications
At the binary level a Decimal number is represented as a coefficient (stored
as an i128 value) combined with a type parameter specifying the number of
fractional decimal digits. I. e., the whole implementation is based on "const
generics" and needs a rust version supporting this feature.
Status
Experimental (work in progess)
Getting started
Add rust-fixed-point-decimal to your Cargo.toml:
[]
= "0.1"
Note:
Because the implementation of "const generics" is still incomplete, you have to put the following at the start of your main.rs or lib.rs file:
Usage
A Decimal number can be created in different ways.
The easiest method is to use the procedural macro Dec:
# use Dec;
let d = Dec!;
assert_eq!;
Alternatively you can convert an integer, a float or a string to a Decimal:
# use Decimal;
let d = from;
assert_eq!;
#
#
# use ;
# use TryFrom;
let d = try_from?;
assert_eq!;
# Ok::
#
#
# use ;
# use FromStr;
let d = from_str?;
assert_eq!;
# Ok::
The sign of a Decimal can be inverted using the unary minus operator and a
Decimal instance can be compared to other instances of type Decimal or all
basic types of integers (besides u128 and atm besides u8, which causes a
compiler error):
#
#
# use ;
let x = Dec!;
let y = -x;
assert_eq!;
assert!;
let z = -y;
assert_eq!;
let z = Dec!;
assert!;
assert!;
assert!;
assert!;
Decimal supports all five binary numerical operators +, -, *, /, and %, with
two Decimals or with a Decimal and a basic integer (besides u128):
#
#
# use ;
let x = Dec!;
let y = Dec!;
let z = x + y;
assert_eq!;
let z = x - y;
assert_eq!;
let z = x * y;
assert_eq!;
let z = x / y;
assert_eq!;
let z = x % y;
assert_eq!;
#
#
# use ;
let x = Dec!;
let y = -5_i64;
let z = x + y;
assert_eq!;
let z = x - y;
assert_eq!;
let z = y * x;
assert_eq!;
let z = x / y;
assert_eq!;
let z = x % y;
assert_eq!;
All these binary numeric operators panic if the result is not representable as
a Decimal according to the constraints stated above. In addition there are
functions implementing "checked" variants of the operators which return
Option::None instead of panicking.
For Multiplication and Division there are also functions which return a result rounded to a number of fractional digits determined by the target type:
#
#
# use ;
let x = Dec!;
let y = Dec!;
let z: = x.mul_rounded;
assert_eq!;
let z: = x.div_rounded;
assert_eq!;