### 32 stable releases

new 1.16.0 | Sep 14, 2021 |
---|---|

1.15.0 | Jul 28, 2021 |

1.14.3 | Jun 19, 2021 |

1.10.3 | Feb 15, 2021 |

0.6.1 | Nov 11, 2017 |

#**6** in Data structures

**27,524** downloads per month

Used in **25** crates
(19 directly)

**MIT**license

300KB

6K
SLoC

# Decimal

A Decimal implementation written in pure Rust suitable for financial calculations that require significant integral and fractional digits with no round-off errors.

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

or `normalize`

functions.`round_dp`

## Getting started

To get started, add

and optionally `rust_decimal`

to your `rust_decimal_macros`

:`Cargo .toml`

`[``dependencies``]`
`rust_decimal ``=` `"`1.16`"`
`rust_decimal_macros ``=` `"`1.16`"`

## Usage

Decimal numbers can be created in a few distinct ways. The easiest and most optimal method of creating a Decimal is to use the procedural macro within the

crate:`rust_decimal_macros`

`//` Procedural macros need importing directly
`use` `rust_decimal_macros``::`dec`;`
`let` number `=` `dec!``(``-``1.``23``)``;`
`assert_eq!``(``"`-1.23`"``,` number`.``to_string``(``)``)``;`

Alternatively you can also use one of the Decimal number convenience functions:

`//` Using the prelude can help importing trait based functions (e.g. core::str::FromStr).
`use` `rust_decimal``::``prelude``::``*``;`
`//` Using an integer followed by the decimal points
`let` scaled `=` `Decimal``::`new`(``202``,` `2``)``;`
`assert_eq!``(``"`2.02`"``,` scaled`.``to_string``(``)``)``;`
`//` From a string representation
`let` from_string `=` `Decimal``::`from_str`(``"`2.02`"``)``.``unwrap``(``)``;`
`assert_eq!``(``"`2.02`"``,` from_string`.``to_string``(``)``)``;`
`//` From a string representation in a different base
`let` from_string_base16 `=` `Decimal``::`from_str_radix`(``"`ffff`"``,` `16``)``.``unwrap``(``)``;`
`assert_eq!``(``"`65535`"``,` from_string_base16`.``to_string``(``)``)``;`
`//` Using the `Into` trait
`let` my_int`:` Decimal `=` `3``i32``.``into``(``)``;`
`assert_eq!``(``"`3`"``,` my_int`.``to_string``(``)``)``;`
`//` Using the raw decimal representation
`let` pi `=` `Decimal``::`from_parts`(``1102470952``,` `185874565``,` `1703060790``,` `false``,` `28``)``;`
`assert_eq!``(``"`3.1415926535897932384626433832`"``,` pi`.``to_string``(``)``)``;`

Once you have instantiated your

number you can perform calculations with it just like any other number:`Decimal`

`use` `rust_decimal``::``prelude``::``*``;`
`let` amount `=` `Decimal``::`from_str`(``"`25.12`"``)``.``unwrap``(``)``;`
`let` tax `=` `Decimal``::`from_str`(``"`0.085`"``)``.``unwrap``(``)``;`
`let` total `=` amount `+` `(`amount `*` tax`)``.``round_dp``(``2``)``;`
`assert_eq!``(`total`.``to_string``(``)``,` `"`27.26`"``)``;`

## Features

- c-repr
- db-postgres
- db-tokio-postgres
- db-diesel-postgres
- legacy-ops
- maths
- rust-fuzz
- serde-float
- serde-str
- serde-arbitrary-precision
- std

`c-repr`

`c-repr`

Forces

to use `Decimal`

. The corresponding target layout is 128 bit aligned.`[``repr``(`C`)``]`

`db-postgres`

`db-postgres`

This feature enables a PostgreSQL communication module. It allows for reading and writing the

type by transparently serializing/deserializing into the `Decimal`

data type within PostgreSQL.`NUMERIC`

`db-tokio-postgres`

`db-tokio-postgres`

Enables the tokio postgres module allowing for async communication with PostgreSQL.

`db-diesel-postgres`

`db-diesel-postgres`

Enable

PostgreSQL support.`diesel`

`legacy-ops`

`legacy-ops`

As of

the algorithms used to perform basic operations have changed which has benefits of significant speed improvements.
To maintain backwards compatibility this can be opted out of by enabling the `1.``10`

feature.`legacy-ops`

`maths`

`maths`

The

feature enables additional complex mathematical functions such as `maths`

, `pow`

, `ln`

, `enf`

etc.
Documentation detailing the additional functions can be found on the
`exp`

trait.`MathematicalOps`

Please note that

and `ln`

will panic on invalid input with `log10`

and `checked_ln`

the preferred functions
to curb against this. When the `checked_log10`

feature was first developed the library would return `maths`

on invalid input. To re-enable this
non-panicing behavior, please use the feature: `0`

.`maths-nopanic`

`rust-fuzz`

`rust-fuzz`

Enable

support by implementing the `rust-fuzz`

trait.`Arbitrary`

`serde-float`

`serde-float`

Enable this so that JSON serialization of

types are sent as a float instead of a string (default).`Decimal`

e.g. with this turned on, JSON serialization would output:

`{`
`"`value`"``:` `1.``234`
`}`

`serde-str`

`serde-str`

This is typically useful for

or `bincode`

like implementations.`csv`

Since

does not specify type information, we need to ensure that a type hint is provided in order to
correctly be able to deserialize. Enabling this feature on its own will force deserialization to use `bincode`

instead of `deserialize_str`

.`deserialize_any`

If, for some reason, you also have

enabled then this will use `serde-float`

as a type hint. Because
converting to `deserialize_f64``f64`*loses* precision, it's highly recommended that you do NOT enable this feature when working with

. That being said, this will only use 8 bytes so is slightly more efficient in terms of storage size.`bincode`

`serde-arbitrary-precision`

`serde-arbitrary-precision`

This is used primarily with

and consequently adds it as a "weak dependency". This supports the
`serde_json`

feature inside `arbitrary_precision`

when parsing decimals.`serde_json`

This is recommended when parsing "float" looking data as it will prevent data loss.

`std`

`std`

Enable

library support. This is enabled by default, however in the future will be opt in. For now, to support `std`

libraries, this crate can be compiled with `no_std`

.`--no-default-features`

## Building

Please refer to the Build document for more information on building and testing Rust Decimal.

## Minimum Rust Compiler Version

This library maintains support for rust compiler versions at least one year old and only updates the minimum version if and
when required. The current minimum compiler version is

which was released on `1.``46``.``0`

.`2020``-``08``-``27`

#### Dependencies

~340–570KB

~11K SLoC