Tech News
← Back to articles

A real fixed-point decimal crate in Rust

read original related products more articles

Primitive fixed-point decimal types.

Rust built-in f32 and f64 types have two drawbacks:

can not represent decimal numbers in base 10 accurately, because they are in base 2; can not guarantee the fraction precision, because they are floating-point.

This crate provides fixed-point decimal types to address the issues by

using integer types to represent numbers with a scaling factor (also called as "scale") in base 10 to achieve the accuracy. This is a common idea. Many other decimal crates do the same thing; specifying the scale staticly to guarantee the fraction precision. The scale is bound to the decimal type. It's fixed-point. Surprisingly, it seems that no crate has done this before.

For example, ConstScaleFpdec means using i64 as the underlying representation, and 4 is the static scale.

The "primitive" in the crate name means straightforward representation, compact memory layout, high performance, and clean APIs, just like Rust's primitive number types.

This crate is no_std .

Distinctive

Although other decimal crates also claim to be fixed-point, they all bind the scale to each decimal instance, which changes during operations. They're more like decimal floating point. See the comparison documentation for details.

... continue reading