| 1 |
# bigdecimal-rs |
| 2 |
|
| 3 |
|
| 4 |
[](https://crates.io/crates/bigdecimal) |
| 5 |
[](https://docs.rs/bigdecimal) |
| 6 |
|
| 7 |
[](https://rust-lang.github.io/rfcs/2495-min-rust-version.html) |
| 8 |
|
| 9 |
[](https://codecov.io/gh/akubera/bigdecimal-rs) |
| 10 |
[](https://gitlab.com/akubera/bigdecimal-rs/-/pipelines) |
| 11 |
[](https://gitlab.com/akubera/bigdecimal-rs/-/pipelines) |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
Arbitrary-precision decimal numbers implemented in pure Rust. |
| 16 |
|
| 17 |
## Community |
| 18 |
|
| 19 |
Join the conversation on Zulip: https://bigdecimal-rs.zulipchat.com |
| 20 |
|
| 21 |
Please share important stuff like use-cases, issues, benchmarks, and |
| 22 |
naming-convention preferences. |
| 23 |
|
| 24 |
This project is currently being re-written, so if performance or flexibility |
| 25 |
is lacking, check again soon and it may be fixed. |
| 26 |
|
| 27 |
## Usage |
| 28 |
|
| 29 |
Add bigdecimal as a dependency to your `Cargo.toml` file: |
| 30 |
|
| 31 |
```toml |
| 32 |
[dependencies] |
| 33 |
bigdecimal = "0.4" |
| 34 |
``` |
| 35 |
|
| 36 |
Import and use the `BigDecimal` struct to solve your problems: |
| 37 |
|
| 38 |
```rust |
| 39 |
use bigdecimal::BigDecimal; |
| 40 |
|
| 41 |
fn main() { |
| 42 |
let two = BigDecimal::from(2); |
| 43 |
println!("sqrt(2) = {}", two.sqrt().unwrap()); |
| 44 |
} |
| 45 |
``` |
| 46 |
|
| 47 |
this code will print |
| 48 |
|
| 49 |
``` |
| 50 |
sqrt(2) = 1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573 |
| 51 |
``` |
| 52 |
|
| 53 |
### Serialization |
| 54 |
|
| 55 |
If you are passing BigDecimals between systems, be sure to use a serialization format |
| 56 |
which explicitly supports decimal numbers and does not require transformations to |
| 57 |
floating-point binary numbers, or there will be information loss. |
| 58 |
|
| 59 |
Text formats like JSON should work ok as long as the receiver will also parse |
| 60 |
numbers as decimals so complete precision is kept accurate. |
| 61 |
Typically JSON-parsing implementations do not do this by default, and need special |
| 62 |
configuration. |
| 63 |
|
| 64 |
Binary formats like msgpack may expect/require representing numbers as 64-bit IEEE-754 |
| 65 |
floating-point, and will likely lose precision by default unless you explicitly format |
| 66 |
the decimal as a string, bytes, or some custom structure. |
| 67 |
|
| 68 |
By default, this will serialize the decimal _as a string_. |
| 69 |
|
| 70 |
To use `serde_json` with this crate it is recommended to enable the `serde-json` feature |
| 71 |
(note `serde -dash- json` , not `serde_json`) and that will add support for |
| 72 |
serializing & deserializing values to BigDecimal. |
| 73 |
By default it will parse numbers and strings using normal conventions. |
| 74 |
If you want to serialize to a number, rather than a string, you can use the |
| 75 |
`serde(with)` annotation as shown in the following example: |
| 76 |
|
| 77 |
```toml |
| 78 |
[dependencies] |
| 79 |
bigdecimal = { version = "0.4", features = [ "serde-json" ] } # '-' not '_' |
| 80 |
``` |
| 81 |
|
| 82 |
```rust |
| 83 |
use bigdecimal::BigDecimal; |
| 84 |
use serde::*; |
| 85 |
use serde_json; |
| 86 |
|
| 87 |
#[derive(Debug,Serialize,Deserialize)] |
| 88 |
struct MyStruct { |
| 89 |
name: String, |
| 90 |
// this will be written to json as string |
| 91 |
value: BigDecimal, |
| 92 |
// this will be written to json as number |
| 93 |
#[serde(with = "bigdecimal::serde::json_num")] |
| 94 |
number: BigDecimal, |
| 95 |
} |
| 96 |
|
| 97 |
fn main() { |
| 98 |
let json_src = r#" |
| 99 |
{ "name": "foo", "value": 1234567e-3, "number": 3.14159 } |
| 100 |
"#; |
| 101 |
|
| 102 |
let my_struct: MyStruct = serde_json::from_str(&json_src).unwrap(); |
| 103 |
dbg!(my_struct); |
| 104 |
// MyStruct { name: "foo", value: BigDecimal("1234.567"), BigDecimal("3.1459") } |
| 105 |
|
| 106 |
println!("{}", serde_json::to_string(&my_struct)); |
| 107 |
// {"name":"foo","value":"1234.567","number":3.1459} |
| 108 |
} |
| 109 |
``` |
| 110 |
|
| 111 |
If you have suggestions for improving serialization, please bring them |
| 112 |
to the Zulip chat. |
| 113 |
|
| 114 |
### Formatting |
| 115 |
|
| 116 |
Until a more sophisticated formatting solution is implemented (currently work in progress), |
| 117 |
we are restricted to Rust's `fmt::Display` formatting options. |
| 118 |
This is how this crate formats BigDecimals: |
| 119 |
|
| 120 |
- `{}` - Default Display |
| 121 |
- Format as "human readable" number |
| 122 |
- "Small" fractional numbers (close to zero) are printed in scientific notation |
| 123 |
- Number is considered "small" by number of leading zeros exceeding a threshold |
| 124 |
- Configurable by the compile-time environment variable: |
| 125 |
`RUST_BIGDECIMAL_FMT_EXPONENTIAL_LOWER_THRESHOLD` |
| 126 |
- Default 5 |
| 127 |
- Example: `1.23e-3` will print as `0.00123` but `1.23e-10` will be `1.23E-10` |
| 128 |
- Trailing zeros will be added to "small" integers, avoiding scientific notation |
| 129 |
- May appear to have more precision than they do |
| 130 |
- Example: decimal `1e1` would be rendered as `10` |
| 131 |
- The threshold for "small" is configured by compile-time environment variable: |
| 132 |
`RUST_BIGDECIMAL_FMT_EXPONENTIAL_UPPER_THRESHOLD` |
| 133 |
- Default 15 |
| 134 |
- `1e15` => `1000000000000000` |
| 135 |
- Large integers (e.g. `1e50000000`) will print in scientific notation, not |
| 136 |
a 1 followed by fifty million zeros |
| 137 |
- All other numbers are printed in standard decimal notation |
| 138 |
|
| 139 |
- `{:.<PREC>}` - Display with precision |
| 140 |
- Format number with exactly `PREC` digits after the decimal place |
| 141 |
- Numbers with fractional components will be rounded at precision point, or have |
| 142 |
zeros padded to precision point |
| 143 |
- Integers will have zeros padded to the precision point |
| 144 |
- To prevent unreasonably sized output, a threshold limits the number |
| 145 |
of padded zeros |
| 146 |
- Greater than the default case, since specific precision was requested |
| 147 |
- Configurable by the compile-time environment variable: |
| 148 |
`RUST_BIGDECIMAL_FMT_MAX_INTEGER_PADDING` |
| 149 |
- Default 1000 |
| 150 |
- If digits exceed this threshold, they are printed without decimal-point, |
| 151 |
suffixed with scale of the big decimal |
| 152 |
|
| 153 |
- `{:e}` / `{:E}` - Exponential format |
| 154 |
- Formats in scientific notation with either `e` or `E` as exponent delimiter |
| 155 |
- Precision is kept exactly |
| 156 |
|
| 157 |
- `{:.<PREC>e}` - formats in scientific notation, keeping number |
| 158 |
- Number is rounded / zero padded until |
| 159 |
|
| 160 |
- `{:?}` - Debug |
| 161 |
- Shows internal representation of BigDecimal |
| 162 |
- `123.456` => `BigDecimal(sign=Plus, scale=3, digits=[123456])` |
| 163 |
- `-1e10000` => `BigDecimal(sign=Minus, scale=-10000, digits=[1])` |
| 164 |
|
| 165 |
- `{:#?}` - Alternate Debug (used by `dbg!()`) |
| 166 |
- Shows simple int+exponent string representation of BigDecimal |
| 167 |
- `123.456` => `BigDecimal("123456e-3")` |
| 168 |
- `-1e10000` => `BigDecimal("-1e10000")` |
| 169 |
|
| 170 |
There is a [formatting-example](examples/formatting-examples.rs) script in the |
| 171 |
`examples/` directory that demonstrates the formatting options and comparison |
| 172 |
with Rust's standard floating point Display. |
| 173 |
|
| 174 |
It is recommended you include unit tests in your code to guarantee that future |
| 175 |
versions of BigDecimal continue to format numbers the way you expect. |
| 176 |
The rules above are not likely to change, but they are probably the only part |
| 177 |
of this library that are relatively subjective, and could change behavior |
| 178 |
without indication from the compiler. |
| 179 |
|
| 180 |
Also, check for changes to the configuration environment variables, those |
| 181 |
may change name until 1.0. |
| 182 |
|
| 183 |
### Compile-Time Configuration |
| 184 |
|
| 185 |
You can set a few default parameters at _compile-time_ via environment variables: |
| 186 |
|
| 187 |
| Environment Variable | Default | |
| 188 |
|----------------------------------------------------|------------| |
| 189 |
| `RUST_BIGDECIMAL_DEFAULT_PRECISION` | 100 | |
| 190 |
| `RUST_BIGDECIMAL_DEFAULT_ROUNDING_MODE` | `HalfEven` | |
| 191 |
| `RUST_BIGDECIMAL_FMT_EXPONENTIAL_LOWER_THRESHOLD` | 5 | |
| 192 |
| `RUST_BIGDECIMAL_FMT_EXPONENTIAL_UPPER_THRESHOLD` | 15 | |
| 193 |
| `RUST_BIGDECIMAL_FMT_MAX_INTEGER_PADDING` | 1000 | |
| 194 |
|
| 195 |
These allow setting the default [Context] fields globally without incurring a runtime lookup, |
| 196 |
or having to pass Context parameters through all calculations. |
| 197 |
(If you want runtime control over these fields, you will have to pass Contexts to your functions.) |
| 198 |
Examine [build.rs] for how those are converted to constants in the code (if interested). |
| 199 |
|
| 200 |
[Context]: https://docs.rs/bigdecimal/latest/bigdecimal/struct.Context.html |
| 201 |
[build.rs]: ./build.rs |
| 202 |
|
| 203 |
|
| 204 |
#### Default precision |
| 205 |
|
| 206 |
Default precision may be set at compile time with the environment variable `RUST_BIGDECIMAL_DEFAULT_PRECISION`. |
| 207 |
The default value of this variable is 100. |
| 208 |
|
| 209 |
This will be used as maximum precision for operations which may produce infinite digits (inverse, sqrt, ...). |
| 210 |
|
| 211 |
Note that other operations, such as multiplication, will preserve all digits; |
| 212 |
so multiplying two 70 digit numbers will result in one 140 digit number. |
| 213 |
The user will have to manually trim the number of digits after calculations to |
| 214 |
reasonable amounts using the `x.with_prec(30)` method. |
| 215 |
|
| 216 |
A new set of methods with explicit precision and rounding modes is being worked |
| 217 |
on, but even after those are introduced the default precision will have to be |
| 218 |
used as the implicit value. |
| 219 |
|
| 220 |
#### Rounding mode |
| 221 |
|
| 222 |
The default Context uses this value for rounding. |
| 223 |
Valid values are the variants of the [RoundingMode] enum. |
| 224 |
|
| 225 |
Defaults to `HalfEven`. |
| 226 |
|
| 227 |
[RoundingMode]: https://docs.rs/bigdecimal/latest/bigdecimal/rounding/enum.RoundingMode.html |
| 228 |
|
| 229 |
|
| 230 |
#### Exponential Format Threshold |
| 231 |
|
| 232 |
The maximum number of leading zeros after the decimal place before |
| 233 |
the formatter uses exponential form (i.e. scientific notation). |
| 234 |
|
| 235 |
There is currently no mechanism to change this during runtime. |
| 236 |
If you know of a good solution for number formatting in Rust, please let me know! |
| 237 |
|
| 238 |
|
| 239 |
#### Example Compile time configuration |
| 240 |
|
| 241 |
Given the program: |
| 242 |
|
| 243 |
```rust |
| 244 |
fn main() { |
| 245 |
let n = BigDecimal::from(700); |
| 246 |
println!("1/{n} = {}", n.inverse()); |
| 247 |
} |
| 248 |
``` |
| 249 |
|
| 250 |
Compiling with different environment variables prints different results |
| 251 |
|
| 252 |
``` |
| 253 |
$ export BIG_DECIMAL_DEFAULT_PRECISION=8 |
| 254 |
$ cargo run |
| 255 |
1/700 = 0.0014285714 |
| 256 |
|
| 257 |
$ export RUST_BIGDECIMAL_DEFAULT_PRECISION=5 |
| 258 |
$ cargo run |
| 259 |
1/700 = 0.0014286 |
| 260 |
|
| 261 |
$ export RUST_BIGDECIMAL_DEFAULT_ROUNDING_MODE=Down |
| 262 |
$ cargo run |
| 263 |
1/700 = 0.0014285 |
| 264 |
|
| 265 |
$ export RUST_BIGDECIMAL_EXPONENTIAL_FORMAT_THRESHOLD=2 |
| 266 |
$ cargo run |
| 267 |
1/700 = 1.4285E-3 |
| 268 |
``` |
| 269 |
|
| 270 |
> [!NOTE] |
| 271 |
> |
| 272 |
> These are **compile time** environment variables, and the BigDecimal |
| 273 |
> library is not configurable at **runtime** via environment variable, or |
| 274 |
> any kind of global variables, by default. |
| 275 |
> |
| 276 |
> This is for flexibility and performance. |
| 277 |
|
| 278 |
|
| 279 |
## About |
| 280 |
|
| 281 |
This repository contains code originally meant for a bigdecimal module |
| 282 |
in the popular [num](https://crates.io/crates/num) crate, but was not |
| 283 |
merged due to uncertainty of what the best design for such a crate |
| 284 |
should be. |
| 285 |
|
| 286 |
|
| 287 |
## License |
| 288 |
|
| 289 |
This code is dual-licensed under the permissive |
| 290 |
[MIT](https://opensource.org/licenses/MIT) & |
| 291 |
[Apache 2.0](https://opensource.org/licenses/Apache-2.0) licenses. |
| 292 |
|
| 293 |
### Contribution |
| 294 |
|
| 295 |
Unless you explicitly state otherwise, any contribution intentionally |
| 296 |
submitted for inclusion in the work by you, as defined in the |
| 297 |
Apache-2.0 license, shall be dual licensed as above, without any |
| 298 |
additional terms or conditions. |