A real fixed-point decimal crate in Rust

https://news.ycombinator.com/rss Hits: 1
Summary

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<i64, 4> 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. While this crate binds the scale to decimal type. The decimal types keep their scale for their whole lifetime instead of changing their scale during operations. The + , - and comparison operations only perform between same types in same scale. There is no implicitly type or scale conversion. This makes sence, for we do not want to add balance type by fee-rate type. Even for two balance types we do not want to add USD currency by CNY. This also makes the operations very fast. However, the * and / operations accept operand with different types and scales, and allow the result's scale specified. Certainly we need to multiply between balance type and fee-rate type and get balance type. If each decimal type has a fixed scale in you application, whic...

First seen: 2025-06-20 04:22

Last seen: 2025-06-20 04:22