Expand description
A Fixed-point decimal implementation written in Rust suitable for a wide range of financial calculations that require significant integral and fractional digits to follow decimal arithmetic rounding.
The binary representation consists of a 64 bit integer number, multiplied by power of 10 - default 10000 for ‘Amount64’ type.
Such implementation results in highly efficient addition and subtraction which are implemented as native operations on i64. These operations also don’t result in any rounding errors.
Multiplication and division are also relatively efficient and implemented via operations on i128 type internally. On some platforms (like x86-64) where 64 x 64 bit multiplication with 128 bit result and division of 128 bit integer by 64 bit are implemented as native instructions, performance penalty compared to regular i64 division and multiplication is negligible.
While 4 fractional decimal digits handles most of cases for accounting and tax computations, in some cases like exchange rates higher precision is desirable. To address this, a sibling type ‘Rate’ is introduced with 8 fractional digits.
§Usage
The stable version of rust requires you to create a Decimal number using one of its convenience methods.
use fin_decimal::Amount64;
use core::str::FromStr;
// Using an integer number.
let from_int = Amount64::from(3); // 3.0000
// Using a floating point number.
let from_f64 = Amount64::from(2.02f64); // 2.0200
// From a string representation
let from_string = Amount64::from_str("2.02").unwrap(); // 2.0200
// Using the `Into` trait
let my_int : Amount64 = 3i32.into();Structs§
- Decimal
- Amount64 type implements decimal fixed-point arithmetic for financial computations. It is implemented to be as efficient as possible with most common add/sub operations to be native binary add/sub. Actual decimal processing is needed for multiplication and division where rounding should follow specific rules. Number of decimal points is chosen to be 4 - this seems to be enough for most use cases except for exchange rates where sometimes up to 8 decimal digits is required
Enums§
- Amount
Error Kind - Enum to store the various types of errors that can cause parsing an integer to fail.
- Amount
Sign - Defines how to display the sign of the parsed number.
- Rounding
Roundingrepresents the different strategies that can be used.
Functions§
- parse_
decimal_ i64 - Converts a string in base 10 to a fixed-point scaled value. Can be used with non-default scale to handle higher precision exchange rates and other scenarios with longer fractional parts.
- str_i64
- Converts an i64 to a fixed-point string representation, optionally padded.