Rust高精度十进制计算库decimal-rs的使用,支持财务计算和精确浮点数运算的Rust插件库
Rust高精度十进制计算库decimal-rs的使用
decimal-rs是一个用于财务计算和精确浮点数运算的Rust库,它提供了高精度的十进制运算能力,避免了传统浮点数运算中的精度问题。
安装
在项目目录中运行以下Cargo命令:
cargo add decimal-rs
或者在Cargo.toml中添加:
decimal-rs = "0.1.43"
基本使用示例
use decimal_rs::Decimal;
fn main() {
// 创建Decimal数值
let a = Decimal::new(12345, 2); // 123.45
let b = Decimal::new(67890, 3); // 67.890
// 加法运算
let sum = a + b;
println!("{} + {} = {}", a, b, sum); // 123.45 + 67.890 = 191.340
// 减法运算
let diff = a - b;
println!("{} - {} = {}", a, b, diff); // 123.45 - 67.890 = 55.560
// 乘法运算
let product = a * b;
println!("{} * {} = {}", a, b, product); // 123.45 * 67.890 = 8380.4205
// 除法运算
let quotient = a / b;
println!("{} / {} = {}", a, b, quotient); // 123.45 / 67.890 ≈ 1.818382
// 比较运算
if a > b {
println!("{} is greater than {}", a, b);
} else {
println!("{} is less than or equal to {}", a, b);
}
}
财务计算示例
use decimal_rs::Decimal;
fn calculate_interest(principal: Decimal, rate: Decimal, years: i32) -> Decimal {
// 计算复利: A = P(1 + r)^t
let one = Decimal::new(100000, 5); // 1.00000
let rate_factor = one + (rate / Decimal::new(10000, 4)); // 1 + (rate/100)
let mut amount = principal;
for _ in 0..years {
amount = amount * rate_factor;
}
amount
}
fn main() {
let principal = Decimal::new(1000000, 2); // 10,000.00
let annual_rate = Decimal::new(500, 2); // 5.00 (%)
let years = 10;
let final_amount = calculate_interest(principal, annual_rate, years);
println!("Initial: {}", principal);
println!("After {} years at {}%: {}", years, annual_rate, final_amount);
}
完整示例代码
下面是一个结合基本运算和财务计算的完整示例:
use decimal_rs::Decimal;
fn main() {
// 示例1:基本运算演示
println!("=== 基本运算演示 ===");
let x = Decimal::new(314159, 5); // 3.14159
let y = Decimal::new(271828, 5); // 2.71828
println!("x = {}, y = {}", x, y);
println!("x + y = {}", x + y); // 5.85987
println!("x - y = {}", x - y); // 0.42331
println!("x * y = {}", x * y); // 8.53972 (约等于3.14159 * 2.71828)
println!("x / y = {}", x / y); // 1.15570 (约等于3.14159 / 2.71828)
// 示例2:财务计算 - 贷款分期付款
println!("\n=== 贷款分期付款计算 ===");
let loan_amount = Decimal::new(10000000, 2); // 100,000.00
let annual_rate = Decimal::new(495, 2); // 4.95%
let months = 36;
let monthly_payment = calculate_monthly_payment(loan_amount, annual_rate, months);
println!("贷款金额: {}", loan_amount);
println!("年利率: {}%", annual_rate);
println!("贷款期限: {}个月", months);
println!("每月还款额: {}", monthly_payment);
}
/// 计算等额本息每月还款额
/// P: 贷款本金
/// r: 月利率
/// n: 还款月数
/// 每月还款额 = [P×r×(1+r)^n]÷[(1+r)^n−1]
fn calculate_monthly_payment(principal: Decimal, annual_rate: Decimal, months: i32) -> Decimal {
let monthly_rate = annual_rate / Decimal::new(1200, 3); // 年利率转为月利率
let one = Decimal::new(100000, 5); // 1.0
let rate_plus_one = one + monthly_rate;
let pow_factor = rate_plus_one.pow(months);
(principal * monthly_rate * pow_factor) / (pow_factor - one)
}
特性
- 高精度十进制运算
- 避免浮点数精度问题
- 适用于财务计算
- 支持基本算术运算和比较
- 可配置的精度
decimal-rs特别适合需要精确计算的金融应用程序、会计系统和任何需要避免浮点数舍入误差的场景。
1 回复
Rust高精度十进制计算库decimal-rs使用指南
decimal-rs是一个用于Rust的高精度十进制计算库,特别适合财务计算和需要精确浮点数运算的场景。
安装
在Cargo.toml中添加依赖:
[dependencies]
decimal-rs = "2.0"
基本使用
创建Decimal值
use decimal_rs::Decimal;
// 从整数创建
let a = Decimal::from(12345);
// 从字符串创建(推荐方式,避免浮点精度问题)
let b = Decimal::from_str("123.456").unwrap();
// 从浮点数创建(可能有精度损失)
let c = Decimal::from_f64(123.456).unwrap();
基本运算
let a = Decimal::from_str("10.50").unwrap();
let b = Decimal::from_str("2.00").unwrap();
// 加法
let sum = a + b; // 12.50
// 减法
let diff = a - b; // 8.50
// 乘法
let product = a * b; // 21.00
// 除法
let quotient = a / b; // 5.25
财务计算示例
计算含税价格
fn calculate_total(price: Decimal, quantity: Decimal, tax_rate: Decimal) -> Decimal {
let subtotal = price * quantity;
let tax = subtotal * tax_rate / Decimal::from(100);
subtotal + tax
}
let price = Decimal::from_str("19.99").unwrap();
let quantity = Decimal::from(3);
let tax_rate = Decimal::from_str("7.5").unwrap();
let total = calculate_total(price, quantity, tax_rate);
println!("Total: {}", total); // 输出: Total: 64.346775
精确货币计算
fn calculate_interest(principal: Decimal, rate: Decimal, days: Decimal) -> Decimal {
let daily_rate = rate / Decimal::from(36500); // 将年利率转换为日利率
principal * daily_rate * days
}
let principal = Decimal::from_str("10000.00").unwrap();
let rate = Decimal::from_str("3.5").unwrap(); // 3.5% 年利率
let days = Decimal::from(30);
let interest = calculate_interest(principal, rate, days);
println!("30天利息: {:.6}", interest); // 输出: 30天利息: 28.767123
高级功能
精度控制
let a = Decimal::from_str("1.23456789").unwrap();
let b = Decimal::from_str("9.87654321").unwrap();
// 设置运算精度为6位小数
let result = a.mul_with_precision(b, 6).unwrap();
println!("{}", result); // 输出: 12.193263
比较和四舍五入
let value = Decimal::from_str("123.456789").unwrap();
// 四舍五入到2位小数
let rounded = value.round_dp(2);
println!("{}", rounded); // 输出: 123.46
// 截断到2位小数
let truncated = value.trunc_dp(2);
println!("{}", truncated); // 输出: 123.45
注意事项
- 优先使用字符串创建Decimal值,避免浮点数精度问题
- 对于财务计算,通常需要设置适当的精度和舍入规则
- Decimal实现了Display trait,可以直接打印
- 支持序列化和反序列化(需要启用serde特性)
decimal-rs提供了财务和科学计算所需的高精度十进制运算能力,是传统浮点数类型的理想替代方案,特别适合需要精确计算的场景。
完整示例代码
use decimal_rs::Decimal;
use std::str::FromStr;
fn main() {
// 示例1: 创建Decimal值
let from_int = Decimal::from(100);
let from_str = Decimal::from_str("123.456").unwrap();
let from_float = Decimal::from_f64(45.6789).unwrap();
println!("从整数创建: {}", from_int);
println!("从字符串创建: {}", from_str);
println!("从浮点数创建: {}", from_float);
// 示例2: 基本运算
let a = Decimal::from_str("15.75").unwrap();
let b = Decimal::from_str("3.25").unwrap();
println!("加法: {}", a + b); // 19.00
println!("减法: {}", a - b); // 12.50
println!("乘法: {}", a * b); // 51.1875
println!("除法: {}", a / b); // 4.846153846153846153846153846
// 示例3: 财务计算
let price = Decimal::from_str("29.99").unwrap();
let quantity = Decimal::from(5);
let tax_rate = Decimal::from_str("8.25").unwrap(); // 8.25%税率
let total = price * quantity;
let tax = total * tax_rate / Decimal::from(100);
let total_with_tax = total + tax;
println!("总价: {}", total);
println!("税额: {:.4}", tax);
println!("含税总价: {:.2}", total_with_tax);
// 示例4: 高级功能 - 精度控制
let x = Decimal::from_str("1.234567").unwrap();
let y = Decimal::from_str("3.141592").unwrap();
let precise_mul = x.mul_with_precision(y, 4).unwrap(); // 保留4位小数
println!("精确乘法结果: {}", precise_mul); // 3.8786
// 示例5: 四舍五入
let value = Decimal::from_str("123.456789").unwrap();
println!("四舍五入2位: {}", value.round_dp(2)); // 123.46
println!("截断2位: {}", value.trunc_dp(2)); // 123.45
// 示例6: 利息计算
let principal = Decimal::from_str("5000.00").unwrap();
let rate = Decimal::from_str("4.25").unwrap(); // 4.25%年利率
let days = Decimal::from(90); // 90天
let interest = principal * rate * days / Decimal::from(36500);
println!("90天利息: {:.6}", interest); // 52.397260
}
这个完整示例展示了decimal-rs库的主要功能:
- 多种创建Decimal值的方式
- 基本算术运算
- 财务相关计算
- 精度控制
- 四舍五入操作
- 利息计算等实际应用
所有示例都遵循decimal-rs的最佳实践,优先使用字符串创建Decimal值以确保精度,并展示了如何控制输出格式和精度。