3 unstable releases
0.2.0 | Jul 14, 2023 |
---|---|
0.1.1 | Jan 14, 2021 |
0.1.0 | Jan 14, 2021 |
#135 in Value formatting
85 downloads per month
Used in 4 crates
(3 directly)
15KB
131 lines
smooth
A utility library for human-readable presentation of numbers.
Rationale
Formatting numbers does not always yield human-readable results:
assert_eq!(format!("{}", 1.0_f64 / 3.0), "0.3333333333333333");
assert_eq!(format!("{}", 2.0_f64.sqrt()), "1.4142135623730951");
When presenting numbers for humans to consume, especially lots of numbers, it may be beneficial to reduce precision to make what's shown comprehensible. This library is intended to be used in user interface (UI) code, inbetween the library, which produces these numbers, and the UI, which presents these numbers to the user, to control the compromise between precision and readability.
Examples
Single Number Smoothing
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");
Multiple Number Smoothing
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"]);
Rounding
In some use cases, rounding to a specific number of decimals might be a better compromise.
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"]);
License
smooth is licensed under either Apache License, Version 2.0 or MIT license, at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.