rust_decimal如何去除末尾零格式化?Display及格式符失效求助
解决rust_decimal去除末尾零的格式化问题
方法1:使用normalize()方法
normalize()会自动移除小数部分末尾的零,若小数部分全为零则同时去掉小数点:
use rust_decimal::Decimal; let d1 = Decimal::from_str("132.10000").unwrap(); println!("{}", d1.normalize()); // 输出 132.1 let d2 = Decimal::from_str("132").unwrap(); println!("{}", d2.normalize()); // 输出 132
方法2:自定义格式化选项
如果需要更精细的精度控制(比如最多保留两位小数,对应.##的效果),可以通过FormatOptions配置:
use rust_decimal::Decimal; use rust_decimal::format::FormatOptions; let opts = FormatOptions::new() .trim_trailing_zeros(true) .precision(2); // 最多保留两位小数 let d1 = Decimal::from_str("132.10000").unwrap(); println!("{}", d1.to_string_with_format(&opts)); // 输出 132.1 let d2 = Decimal::from_str("132.456").unwrap(); println!("{}", d2.to_string_with_format(&opts)); // 输出 132.46(自动四舍五入) let d3 = Decimal::from_str("132").unwrap(); println!("{}", d3.to_string_with_format(&opts)); // 输出 132
方法3:扩展标准格式化语法
rust_decimal支持在标准格式化语法中添加trim参数,实现去除末尾零的效果:
use rust_decimal::Decimal; let d1 = Decimal::from_str("132.10000").unwrap(); println!("{:.trim}", d1); // 输出 132.1 let d2 = Decimal::from_str("132.000").unwrap(); println!("{:.trim}", d2); // 输出 132 // 结合精度控制,最多保留两位小数并去零 let d3 = Decimal::from_str("132.4500").unwrap(); println!("{:.2trim}", d3); // 输出 132.45 let d4 = Decimal::from_str("132.4000").unwrap(); println!("{:.2trim}", d4); // 输出 132.4
以上方法分别对应Java DecimalFormat("0")、.NET ToString("0.##")的格式化效果。
内容的提问来源于stack exchange,提问作者Nil Admirari
相关产品推荐
相关产品推荐

