13个稳定版本
1.7.0 | 2020年7月11日 |
---|---|
1.4.1 | 2020年4月10日 |
1.4.0 | 2020年3月23日 |
1.1.0 | 2019年12月27日 |
0.11.1 | 2019年2月11日 |
#29 in #financial
每月105次下载
385KB
8K SLoC
Decimal

一个纯Rust编写的Decimal实现,适用于需要大量整数和小数位且没有舍入误差的金融计算。
二进制表示由一个96位整数、一个用于指定小数分数的缩放因子和一个1位符号组成。由于这种表示,尾随零被保留,在字符串形式下可能被显示。这些可以使用normalize
或round_dp
函数截断。
用法
Decimal数字可以通过几种不同的方式创建。创建Decimal最简单和最优的方法是使用rust_decimal_macros
crate中的过程宏
// Procedural macros need importing directly
use rust_decimal_macros::*;
let number = dec!(-1.23);
或者你也可以使用Decimal数字便利函数之一
use rust_decimal::prelude::*;
// Using an integer followed by the decimal points
let scaled = Decimal::new(202, 2); // 2.02
// From a string representation
let from_string = Decimal::from_str("2.02").unwrap(); // 2.02
// Using the `Into` trait
let my_int : Decimal = 3i32.into();
// Using the raw decimal representation
// 3.1415926535897932384626433832
let pi = Decimal::from_parts(1102470952, 185874565, 1703060790, false, 28);
功能
db-postgres
此功能启用了一个PostgreSQL通信模块。它允许通过透明地序列化和反序列化到PostgreSQL中的NUMERIC
数据类型来读取和写入Decimal
类型。
db-tokio-postgres
启用tokio postgres模块,允许异步与PostgreSQL通信。
db-diesel-postgres
启用diesel
对PostgreSQL的支持。
serde-float
启用此功能,以便将Decimal类型的JSON序列化发送为浮点数而不是字符串(默认)。
例如,启用此功能后,JSON序列化将输出
{
"value": 1.234
}
serde-bincode
由于 bincode
没有指定类型信息,我们需要确保提供类型提示,才能正确反序列化。单独启用此功能将强制使用 deserialize_str
而不是 deserialize_any
进行反序列化。
如果您出于某种原因还启用了 serde-float
,那么它将使用 deserialize_f64
作为类型提示。由于将 f64
转换会 丢失 精度,强烈建议在处理 bincode
时不要启用此功能。尽管如此,这只会使用 8 字节,因此在存储大小方面略微更高效。
依赖项
~285–640KB
~13K SLoC