| 1 |
# Decimal   [![Build Status]][actions] [![Latest Version]][crates.io] [![Docs Badge]][docs] |
| 2 |
|
| 3 |
[Build Status]: https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fpaupino%2Frust-decimal%2Fbadge&label=build&logo=none |
| 4 |
[actions]: https://actions-badge.atrox.dev/paupino/rust-decimal/goto |
| 5 |
[Latest Version]: https://img.shields.io/crates/v/rust-decimal.svg |
| 6 |
[crates.io]: https://crates.io/crates/rust-decimal |
| 7 |
[Docs Badge]: https://docs.rs/rust_decimal/badge.svg |
| 8 |
[docs]: https://docs.rs/rust_decimal |
| 9 |
|
| 10 |
A Decimal number implementation written in pure Rust suitable for financial calculations that require significant integral and fractional digits with no round-off errors. |
| 11 |
|
| 12 |
The binary representation consists of a 96 bit integer number, a scaling factor used to specify the decimal fraction and a 1 bit sign. Because of this representation, trailing zeros are preserved and may be exposed when in string form. These can be truncated using the `normalize` or `round_dp` functions. |
| 13 |
|
| 14 |
## Installing |
| 15 |
|
| 16 |
Using [`cargo-edit`](https://crates.io/crates/cargo-edit): |
| 17 |
|
| 18 |
```sh |
| 19 |
$ cargo add rust_decimal |
| 20 |
``` |
| 21 |
|
| 22 |
In addition, if you would like to use the optimized macro for convenient creation of decimals: |
| 23 |
|
| 24 |
```sh |
| 25 |
$ cargo add rust_decimal_macros |
| 26 |
``` |
| 27 |
|
| 28 |
Alternatively, you can edit your `Cargo.toml` directly and run `cargo update`: |
| 29 |
|
| 30 |
```toml |
| 31 |
[dependencies] |
| 32 |
rust_decimal = "1.28" |
| 33 |
rust_decimal_macros = "1.28" |
| 34 |
``` |
| 35 |
|
| 36 |
## Usage |
| 37 |
|
| 38 |
Decimal numbers can be created in a few distinct ways. The easiest and most efficient method of creating a Decimal is to use the procedural macro within the `rust_decimal_macros` crate: |
| 39 |
|
| 40 |
```rust |
| 41 |
// Procedural macros need importing directly |
| 42 |
use rust_decimal_macros::dec; |
| 43 |
|
| 44 |
let number = dec!(-1.23) + dec!(3.45); |
| 45 |
assert_eq!(number, dec!(2.22)); |
| 46 |
assert_eq!(number.to_string(), "2.22"); |
| 47 |
``` |
| 48 |
|
| 49 |
Alternatively you can also use one of the Decimal number convenience functions ([see the docs](https://docs.rs/rust_decimal/) for more details): |
| 50 |
|
| 51 |
```rust |
| 52 |
// Using the prelude can help importing trait based functions (e.g. core::str::FromStr). |
| 53 |
use rust_decimal::prelude::*; |
| 54 |
|
| 55 |
// Using an integer followed by the decimal points |
| 56 |
let scaled = Decimal::new(202, 2); |
| 57 |
assert_eq!("2.02", scaled.to_string()); |
| 58 |
|
| 59 |
// From a 128 bit integer |
| 60 |
let balance = Decimal::from_i128_with_scale(5_897_932_384_626_433_832, 2); |
| 61 |
assert_eq!("58979323846264338.32", balance.to_string()); |
| 62 |
|
| 63 |
// From a string representation |
| 64 |
let from_string = Decimal::from_str("2.02").unwrap(); |
| 65 |
assert_eq!("2.02", from_string.to_string()); |
| 66 |
|
| 67 |
// From a string representation in a different base |
| 68 |
let from_string_base16 = Decimal::from_str_radix("ffff", 16).unwrap(); |
| 69 |
assert_eq!("65535", from_string_base16.to_string()); |
| 70 |
|
| 71 |
// From scientific notation |
| 72 |
let sci = Decimal::from_scientific("9.7e-7").unwrap(); |
| 73 |
assert_eq!("0.00000097", sci.to_string()); |
| 74 |
|
| 75 |
// Using the `Into` trait |
| 76 |
let my_int: Decimal = 3_i32.into(); |
| 77 |
assert_eq!("3", my_int.to_string()); |
| 78 |
|
| 79 |
// Using the raw decimal representation |
| 80 |
let pi = Decimal::from_parts(1_102_470_952, 185_874_565, 1_703_060_790, false, 28); |
| 81 |
assert_eq!("3.1415926535897932384626433832", pi.to_string()); |
| 82 |
``` |
| 83 |
|
| 84 |
Once you have instantiated your `Decimal` number you can perform calculations with it just like any other number: |
| 85 |
|
| 86 |
```rust |
| 87 |
use rust_decimal::prelude::*; |
| 88 |
use rust_decimal_macros::dec; |
| 89 |
|
| 90 |
let amount = dec!(25.12); |
| 91 |
let tax_percentage = dec!(0.085); |
| 92 |
let total = amount + (amount * tax_percentage).round_dp(2); |
| 93 |
assert_eq!(total, dec!(27.26)); |
| 94 |
``` |
| 95 |
|
| 96 |
## Features |
| 97 |
|
| 98 |
**Behavior / Functionality** |
| 99 |
|
| 100 |
* [borsh](#borsh) |
| 101 |
* [c-repr](#c-repr) |
| 102 |
* [legacy-ops](#legacy-ops) |
| 103 |
* [maths](#maths) |
| 104 |
* [rkyv](#rkyv) |
| 105 |
* [rocket-traits](#rocket-traits) |
| 106 |
* [rust-fuzz](#rust-fuzz) |
| 107 |
* [std](#std) |
| 108 |
|
| 109 |
**Database** |
| 110 |
|
| 111 |
* [db-postgres](#db-postgres) |
| 112 |
* [db-tokio-postgres](#db-tokio-postgres) |
| 113 |
* [db-diesel-postgres](#db-diesel-postgres) |
| 114 |
* [db-diesel-mysql](#db-diesel-mysql) |
| 115 |
|
| 116 |
**Serde** |
| 117 |
|
| 118 |
* [serde-float](#serde-float) |
| 119 |
* [serde-str](#serde-str) |
| 120 |
* [serde-arbitrary-precision](#serde-arbitrary-precision) |
| 121 |
* [serde-with-float](#serde-with-float) |
| 122 |
* [serde-with-str](#serde-with-str) |
| 123 |
* [serde-with-arbitrary-precision](#serde-with-arbitrary-precision) |
| 124 |
|
| 125 |
### `borsh` |
| 126 |
|
| 127 |
Enables [Borsh](https://borsh.io/) serialization for `Decimal`. |
| 128 |
|
| 129 |
### `c-repr` |
| 130 |
|
| 131 |
Forces `Decimal` to use `[repr(C)]`. The corresponding target layout is 128 bit aligned. |
| 132 |
|
| 133 |
### `db-postgres` |
| 134 |
|
| 135 |
Enables a PostgreSQL communication module. It allows for reading and writing the `Decimal` |
| 136 |
type by transparently serializing/deserializing into the `NUMERIC` data type within PostgreSQL. |
| 137 |
|
| 138 |
### `db-tokio-postgres` |
| 139 |
|
| 140 |
Enables the tokio postgres module allowing for async communication with PostgreSQL. |
| 141 |
|
| 142 |
### `db-diesel-postgres` |
| 143 |
|
| 144 |
Enable `diesel` PostgreSQL support. By default, this enables version `1.4` of `diesel`. If you wish to use the `2.0` |
| 145 |
version of `diesel` then you can do so by using the feature `db-diesel2-postgres`. Please note, if both features are |
| 146 |
enabled then version 2 will supersede version 1. |
| 147 |
|
| 148 |
### `db-diesel-mysql` |
| 149 |
|
| 150 |
Enable `diesel` MySQL support. By default, this enables version `1.4` of `diesel`. If you wish to use the `2.0` |
| 151 |
version of `diesel` then you can do so by using the feature `db-diesel2-mysql`. Please note, if both features are |
| 152 |
enabled then version 2 will supersede version 1. |
| 153 |
|
| 154 |
### `legacy-ops` |
| 155 |
|
| 156 |
**Warning:** This is deprecated and will be removed from a future versions. |
| 157 |
|
| 158 |
As of `1.10` the algorithms used to perform basic operations have changed which has benefits of significant speed improvements. |
| 159 |
To maintain backwards compatibility this can be opted out of by enabling the `legacy-ops` feature. |
| 160 |
|
| 161 |
### `maths` |
| 162 |
|
| 163 |
The `maths` feature enables additional complex mathematical functions such as `pow`, `ln`, `enf`, `exp` etc. |
| 164 |
Documentation detailing the additional functions can be found on the |
| 165 |
[`MathematicalOps`](https://docs.rs/rust_decimal/latest/rust_decimal/trait.MathematicalOps.html) trait. |
| 166 |
|
| 167 |
Please note that `ln` and `log10` will panic on invalid input with `checked_ln` and `checked_log10` the preferred functions |
| 168 |
to curb against this. When the `maths` feature was first developed the library would return `0` on invalid input. To re-enable this |
| 169 |
non-panicking behavior, please use the feature: `maths-nopanic`. |
| 170 |
|
| 171 |
### `rand` |
| 172 |
|
| 173 |
Implements `rand::distributions::Distribution<Decimal>` to allow the creation of random instances. |
| 174 |
|
| 175 |
Note: When using `rand::Rng` trait to generate a decimal between a range of two other decimals, the scale of the randomly-generated |
| 176 |
decimal will be the same as the scale of the input decimals (or, if the inputs have different scales, the higher of the two). |
| 177 |
|
| 178 |
### `rkyv` |
| 179 |
Enables [rkyv](https://github.com/rkyv/rkyv) serialization for `Decimal`. |
| 180 |
Supports rkyv's safe API when the `rkyv-safe` feature is enabled as well. |
| 181 |
|
| 182 |
### `rocket-traits` |
| 183 |
|
| 184 |
Enable support for Rocket forms by implementing the `FromFormField` trait. |
| 185 |
|
| 186 |
### `rust-fuzz` |
| 187 |
|
| 188 |
Enable `rust-fuzz` support by implementing the `Arbitrary` trait. |
| 189 |
|
| 190 |
### `serde-float` |
| 191 |
|
| 192 |
**Note:** it is recommended to use the `serde-with-*` features for greater control. This allows configurability at the data |
| 193 |
level. |
| 194 |
|
| 195 |
Enable this so that JSON serialization of `Decimal` types are sent as a float instead of a string (default). |
| 196 |
|
| 197 |
e.g. with this turned on, JSON serialization would output: |
| 198 |
```json |
| 199 |
{ |
| 200 |
"value": 1.234 |
| 201 |
} |
| 202 |
``` |
| 203 |
|
| 204 |
### `serde-str` |
| 205 |
|
| 206 |
**Note:** it is recommended to use the `serde-with-*` features for greater control. This allows configurability at the data |
| 207 |
level. |
| 208 |
|
| 209 |
This is typically useful for `bincode` or `csv` like implementations. |
| 210 |
|
| 211 |
Since `bincode` does not specify type information, we need to ensure that a type hint is provided in order to |
| 212 |
correctly be able to deserialize. Enabling this feature on its own will force deserialization to use `deserialize_str` |
| 213 |
instead of `deserialize_any`. |
| 214 |
|
| 215 |
If, for some reason, you also have `serde-float` enabled then this will use `deserialize_f64` as a type hint. Because |
| 216 |
converting to `f64` _loses_ precision, it's highly recommended that you do NOT enable this feature when working with |
| 217 |
`bincode`. That being said, this will only use 8 bytes so is slightly more efficient in terms of storage size. |
| 218 |
|
| 219 |
### `serde-arbitrary-precision` |
| 220 |
|
| 221 |
**Note:** it is recommended to use the `serde-with-*` features for greater control. This allows configurability at the data |
| 222 |
level. |
| 223 |
|
| 224 |
This is used primarily with `serde_json` and consequently adds it as a "weak dependency". This supports the |
| 225 |
`arbitrary_precision` feature inside `serde_json` when parsing decimals. |
| 226 |
|
| 227 |
This is recommended when parsing "float" looking data as it will prevent data loss. |
| 228 |
|
| 229 |
### `serde-with-float` |
| 230 |
|
| 231 |
Enable this to access the module for serializing `Decimal` types to a float. This can be use in `struct` definitions like so: |
| 232 |
|
| 233 |
```rust |
| 234 |
#[derive(Serialize, Deserialize)] |
| 235 |
pub struct FloatExample { |
| 236 |
#[serde(with = "rust_decimal::serde::float")] |
| 237 |
value: Decimal, |
| 238 |
} |
| 239 |
``` |
| 240 |
```rust |
| 241 |
#[derive(Serialize, Deserialize)] |
| 242 |
pub struct OptionFloatExample { |
| 243 |
#[serde(with = "rust_decimal::serde::float_option")] |
| 244 |
value: Option<Decimal>, |
| 245 |
} |
| 246 |
``` |
| 247 |
|
| 248 |
### `serde-with-str` |
| 249 |
|
| 250 |
Enable this to access the module for serializing `Decimal` types to a `String`. This can be use in `struct` definitions like so: |
| 251 |
|
| 252 |
```rust |
| 253 |
#[derive(Serialize, Deserialize)] |
| 254 |
pub struct StrExample { |
| 255 |
#[serde(with = "rust_decimal::serde::str")] |
| 256 |
value: Decimal, |
| 257 |
} |
| 258 |
``` |
| 259 |
```rust |
| 260 |
#[derive(Serialize, Deserialize)] |
| 261 |
pub struct OptionStrExample { |
| 262 |
#[serde(with = "rust_decimal::serde::str_option")] |
| 263 |
value: Option<Decimal>, |
| 264 |
} |
| 265 |
``` |
| 266 |
|
| 267 |
### `serde-with-arbitrary-precision` |
| 268 |
|
| 269 |
Enable this to access the module for serializing `Decimal` types to a `String`. This can be use in `struct` definitions like so: |
| 270 |
|
| 271 |
```rust |
| 272 |
#[derive(Serialize, Deserialize)] |
| 273 |
pub struct ArbitraryExample { |
| 274 |
#[serde(with = "rust_decimal::serde::arbitrary_precision")] |
| 275 |
value: Decimal, |
| 276 |
} |
| 277 |
``` |
| 278 |
```rust |
| 279 |
#[derive(Serialize, Deserialize)] |
| 280 |
pub struct OptionArbitraryExample { |
| 281 |
#[serde(with = "rust_decimal::serde::arbitrary_precision_option")] |
| 282 |
value: Option<Decimal>, |
| 283 |
} |
| 284 |
``` |
| 285 |
|
| 286 |
### `std` |
| 287 |
|
| 288 |
Enable `std` library support. This is enabled by default, however in the future will be opt in. For now, to support `no_std` |
| 289 |
libraries, this crate can be compiled with `--no-default-features`. |
| 290 |
|
| 291 |
## Building |
| 292 |
|
| 293 |
Please refer to the [Build document](BUILD.md) for more information on building and testing Rust Decimal. |
| 294 |
|
| 295 |
## Minimum Rust Compiler Version |
| 296 |
|
| 297 |
The current _minimum_ compiler version is [`1.60.0`](https://github.com/rust-lang/rust/blob/master/RELEASES.md#version-1600-2022-04-07) |
| 298 |
which was released on `2022-04-07`. |
| 299 |
|
| 300 |
This library maintains support for rust compiler versions that are 4 minor versions away from the current stable rust compiler version. |
| 301 |
For example, if the current stable compiler version is `1.50.0` then we will guarantee support up to and including `1.46.0`. |
| 302 |
Of note, we will only update the minimum supported version if and when required. |