#numbers #compact #pretty #format #light-weight

pretty-num

A lightweight library for compactly formatting integers

1 unstable release

0.1.0 Aug 10, 2024

#148 in Value formatting

Download history 93/week @ 2024-08-05 45/week @ 2024-08-12 2/week @ 2024-08-19 13/week @ 2024-08-26 23/week @ 2024-09-16 18/week @ 2024-09-23 21/week @ 2024-09-30 3/week @ 2024-10-07 10/week @ 2024-10-14

54 downloads per month

GPL-3.0-or-later

16KB
103 lines

License Last commit GitHub stars

prettty-num

Format integers into a compact social media style format, similar to using Intl.NumberFormat("en", { notation: "compact" }); as a number formatter in Javascript.

Usage

Simply import the PrettyNumber trait into your module to use the pretty_format method on any number that can convert into an i64:

use pretty_num::PrettyNumber;
// Integers with a magnitude less than 1,000 do not get compacted.
assert_eq!(534.pretty_format(), String::from("534"));

// Integers with a magnitude greater than or equal to 1,000 get compacted.
assert_eq!(15_000.pretty_format(), String::from("15k"));

// Integers will have a single decimal point when rounded.
assert_eq!(4_230_542.pretty_format(), String::from("4.2M"));

// Formatted numbers get rounded to a number without a decimal place when appropriate.
assert_eq!(5_031.pretty_format(), String::from("5k"));

// Also works with negative numbers.
assert_eq!((-25_621_783).pretty_format(), String::from("-25.6M"));

// Can go as high as trillions!
assert_eq!(36_777_121_590_100i64.pretty_format(), String::from("36.8T"));

Why use this instead of another number formatting crate?

There are several other number formatting libraries for Rust such as numfmt, 'human_format', si_format, and si-scale. All of these crates are more flexible than this one. However, all of them have a fixed number of decimals. If you want to, for example, have 12 formatted as "12" and 1500 formatted as "1.5k", you will not be able to do so: you can get "2.0" and "1.5k" or "2" and "2k", but they all use an exact number of significant digits/decimal points. If compact numbers that omit the decimal when appropriate is all you need, this is the crate for you. Otherwise, the crates mentioned above are likely more appropriate for your usecase.

No runtime deps