3 个不稳定版本
0.2.0 | 2023年7月14日 |
---|---|
0.1.1 | 2021年1月14日 |
0.1.0 | 2021年1月14日 |
在 值格式化 中排名第 122
每月 30 次下载
在 4 个crate(3 个直接使用)中使用
15KB
131 行
smooth
一个用于数字易读性呈现的实用库。
原理
格式化数字并不总是产生易读的结果
assert_eq!(format!("{}", 1.0_f64 / 3.0), "0.3333333333333333");
assert_eq!(format!("{}", 2.0_f64.sqrt()), "1.4142135623730951");
当向人类呈现数字时,特别是大量数字,减少精度以使显示内容 易于理解 可能是有益的。这个库旨在在生成这些数字的库和将数字呈现给用户的UI之间使用,以 控制精度和可读性之间的权衡。
示例
单个数字平滑处理
use smooth::Smooth;
// numbers without a fraction are simply rounded
assert_eq!(0.0.smooth_str(), "0");
assert_eq!(42.0.smooth_str(), "42");
// numbers with zero integer part are rounded to 2 decimals
assert_eq!(0.1.smooth_str(), "0.1");
assert_eq!(0.09.smooth_str(), "0.09");
assert_eq!(0.009.smooth_str(), "0.01");
assert_eq!(0.001.smooth_str(), "0");
// comparatively large fractions are kept
assert_eq!(1.1.smooth_str(), "1.1");
assert_eq!(1.01.smooth_str(), "1.01");
assert_eq!(10.9.smooth_str(), "10.9");
// comparatively small fractions are smoothed away
assert_eq!(1.001.smooth_str(), "1");
assert_eq!(10.09.smooth_str(), "10.1");
assert_eq!(1000.1.smooth_str(), "1000");
多个数字平滑处理
use smooth::MultiSmooth;
let numbers = [1.1111, 5.5555, 9.9999];
assert_eq!(numbers.smooth_str(), ["1.1", "5.6", "10"]);
let numbers = [1.1111, 5.5555, 1000.0];
assert_eq!(numbers.smooth_str(), ["1", "6", "1000"]);
let numbers = [0.009, 0.249, 0.999];
assert_eq!(numbers.smooth_str(), ["0.01", "0.25", "1"]);
四舍五入
在某些情况下,将数字四舍五入到特定的小数位数可能是一个更好的权衡。
use smooth::{MultiSmooth, Smooth};
// round to a specific number of decimals
assert_eq!(1.0.round_to_str(2), "1");
assert_eq!(1.001.round_to_str(2), "1");
assert_eq!(1.018.round_to_str(2), "1.02");
assert_eq!(1.4242.round_to_str(2), "1.42");
// consistently round multiple numbers
let numbers = [1.1111, 2.2222, 5.5555];
assert_eq!(numbers.round_to_str(2), ["1.11", "2.22", "5.56"]);
许可证
smooth 可以根据您的选择,在 Apache 许可协议,版本 2.0 或 MIT 许可协议 下使用。
贡献
除非您明确声明,否则任何有意提交以包含在作品中的贡献,如 Apache-2.0 许可协议中定义的,应按照上述方式双重许可,不附加任何额外条款或条件。