humanize_proper 0.1.2

Dependency-free, no_std formatting of numbers with SI/binary unit prefixes and of durations
Documentation
  • Coverage
  • 100%
    40 out of 40 items documented9 out of 9 items with examples
  • Size
  • Source code size: 90.1 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 650.6 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 4s Average build duration of successful builds.
  • all releases: 6s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • daniel-x/humanize_proper
    1 0 1
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • daniel-x

humanize_proper

Human readable formatting of numbers and durations for Rust. No dependencies, #![no_std], no allocation, no unsafe.

use humanize_proper::{bin, dur};

println!("downloaded {} in {}", bin(4_823_512), dur(93));
// downloaded 4.6MiB in 01m33s

Numbers

A large number is scaled down until it fits into a few digits, and a unit prefix carries the rest of the magnitude. There are two prefix systems, and the crate lets you pick per call site:

  • decimal (metric, factor 1000), prefixes k M G T P E Z Y R Q, as used for disk capacities, data rates, frequencies and everything else the SI touches.
  • binary (factor 1024), prefixes Ki Mi Gi Ti Pi Ei Zi Yi Ri Qi, as used for file sizes, memory and everything a computer counts in powers of two.
use humanize_proper::{bin, dec};

// A file on disk, the way `ls -lh` shows it.
println!("archive.tar.zst  {}", bin(4_823_512));
// archive.tar.zst  4.6MiB

// A disk's capacity, the way the vendor prints it on the box.
println!("capacity: {}", dec(2_000_398_934_016u64));
// capacity: 2TB

The _no_unit variants drop the trailing B, for counting things that are not bytes:

use humanize_proper::dec_no_unit;

println!("{} rows imported", dec_no_unit(18_500_000));
// 18.5M rows imported

Any other unit is a builder call away, as is the space before the prefix. NumFmt is Copy and all its methods are const, so a format you use in several places can live in a constant:

use humanize_proper::NumFmt;

const RATE: NumFmt = NumFmt::dec().unit("B/s").space(true);

println!("throughput: {}", RATE.fmt(2_411_756));
// throughput: 2.41 MB/s

println!("clock: {}", NumFmt::dec().unit("Hz").fmt(4_700_000_000u64));
// clock: 4.7GHz

println!("word size: {}", NumFmt::bin().jedec().fmt(1536));
// word size: 1.5KB

Values below 1 print as a fraction of the unit, which is what a byte count wants. For measured quantities, .small_prefixes(true) switches them to the SI submultiples m µ n p f a z y r q:

use humanize_proper::NumFmt;

const VOLT: NumFmt = NumFmt::dec().unit("V").small_prefixes(true);

println!("offset: {}", VOLT.fmt(0.0125));
// offset: 12.5mV

println!("noise floor: {}", VOLT.fmt(0.000_000_47));
// noise floor: 470nV

µ is the only prefix outside ASCII. Where that is a problem, .ascii_micro(true) spells it u:

use humanize_proper::NumFmt;

const SEC: NumFmt = NumFmt::dec().unit("s").small_prefixes(true).ascii_micro(true);

println!("latency: {}", SEC.fmt(0.000_002_5));
// latency: 2.5us

Integers are scaled with exact u128 arithmetic. Nothing takes a detour through f64, so rounding rolls over into the next prefix where it should, and even the extremes stay precise:

use humanize_proper::{bin, dec};

println!("{}", dec(999_999));
// 1MB

println!("{}", bin(u64::MAX));
// 16EiB

Options

NumFmt builder, all methods const:

Method Effect Default
NumFmt::bin() factor 1024, IEC prefixes, unit B, no space 1536 -> "1.5KiB"
NumFmt::dec() factor 1000, SI prefixes, unit B, no space 1500 -> "1.5kB"
.base(Base) switches the factor, keeping everything else
.space(bool) space between number and prefix false
.unit(&'static str) unit appended after the prefix "B"
.no_unit() drop the unit
.prefixes(Prefixes), .iec(), .jedec() spelling of the binary prefixes Iec
.small_prefixes(bool) scale values below 1 into m, µ, n, ... false
.ascii_micro(bool) spell the micro prefix u instead of µ false
.sig_digits(u8) significant digits, clamped to 1..=15 3
.trim_zeros(bool) drop trailing fraction zeros and a bare . true
.fmt(value) bind a value, yielding a Display

Prefixes

Table Prefixes
SI, factor 1000 k M G T P E Z Y R Q
SI submultiples, factor 1000 m µ n p f a z y r q
IEC, factor 1024 Ki Mi Gi Ti Pi Ei Zi Yi Ri Qi
JEDEC, factor 1024 K M G T P E Z Y R Q

Prefixes only affects factor 1024; factor 1000 always uses the SI table with its lowercase k. The submultiples are used only with .small_prefixes(true), and only for factor 1000, since the binary prefixes have no counterpart below 1.

Rounding and precision

  • Rounding is half-up and may roll over into the next prefix, e.g. 999_999 -> "1MB".
  • The digit count applies to the integer part, so sig_digits never shortens it: at 1 significant digit, 999 still prints as 999B.
  • Values below 1 carry sig_digits - 1 fraction digits, e.g. 0.125 -> "0.13B". Leading zeros of the fraction are not counted as significant. With .small_prefixes(true) they are scaled into a submultiple instead, e.g. 0.125 -> "125mB", and magnitudes below q round to zero.
  • NaN prints as NaN, infinities as inf and -inf, all three without prefix or unit.
  • Magnitudes beyond the largest prefix, reachable only with floats, print their mantissa plainly.

Accepted input

Every primitive integer type plus f32 and f64, through the ToValue trait. Negative values are printed as - followed by the magnitude. Floats with an exact integer value take the exact integer path.

Durations

The default style is 32y007d_05h01m05s: years and days, then hours, minutes and seconds, with _ between the two groups. Leading units that are zero are dropped, so a short duration stays short.

use humanize_proper::dur;

println!("uptime: {}", dur(3665));
// uptime: 01h01m05s

println!("session ends in {}", dur(90));
// session ends in 01m30s

Zero padding keeps columns aligned, which is what you want in a log or a table. When the duration sits in a sentence instead, trim the padding away:

use humanize_proper::{DurFmt, TimeUnit, Zeros};

const REMAINING: DurFmt = DurFmt::new().zeros(Zeros::TrimLargest).smallest(TimeUnit::Day);

println!("certificate expires in {}", REMAINING.fmt(7_776_000));
// certificate expires in 90d

println!("took {}", DurFmt::new().zeros(Zeros::TrimAll).fmt(3665));
// took 1h1m5s

Zeros::TrimLargest cuts the leading zeros off the largest unit only, so 05h01m05s becomes 5h01m05s and the smaller fields keep their two digits. .smallest(TimeUnit) truncates everything below the given unit.

For timings, the seconds field takes a fraction. core::time::Duration is accepted directly, and for anything finer than nanoseconds the crate has its own Dur type, resolving down to attoseconds:

use core::time::Duration;
use humanize_proper::{dur, Dur, DurFmt, Frac};

println!("{}", dur(Duration::from_millis(90_500)));
// 01m30s

let elapsed = Dur::from_nanos(65_123_456_789);

println!("finished in {}", DurFmt::new().frac(Frac::Millis).fmt(elapsed));
// finished in 01m05.123s

println!("finished in {}", DurFmt::new().frac(Frac::Nanos).fmt(elapsed));
// finished in 01m05.123456789s

println!("one attosecond is {}", DurFmt::new().frac(Frac::Attos).fmt(Dur::from_attos(1)));
// one attosecond is 00.000000000000000001s

Options

DurFmt builder, all methods const:

Method Effect Default
DurFmt::new() the default style 32y007d_05h01m05s
.zeros(Zeros) zero padding mode Pad
.frac(Frac) fractional second precision Secs
.frac_digits(u8) arbitrary fraction width, 0..=18 0
.frac_sep(Option<&'static str>) group fraction digits in threes None
.sep(&'static str), .no_sep() date/time group separator "_"
.smallest(TimeUnit) smallest printed unit, truncating Sec
.secs_per_year(u64) length of a year in seconds 31_556_952
.fmt(duration) bind a duration, yielding a Display

Zero padding

Variant 5h 1m 5s
Zeros::Pad, the default 05h01m05s
Zeros::TrimAll 5h1m5s
Zeros::TrimLargest 5h01m05s

Padding uses the natural width of each unit: 3 digits for days, 2 for hours, minutes and seconds. Years are unbounded and never padded.

Fractional seconds

Variant Digits 65.123456789012345678 s
Frac::Secs, the default 0 01m05s
Frac::Millis 3 01m05.123s
Frac::Micros 6 01m05.123456s
Frac::Nanos 9 01m05.123456789s
Frac::Picos 12 01m05.123456789012s
Frac::Femtos 15 01m05.123456789012345s
Frac::Attos 18 01m05.123456789012345678s

The fraction is truncated rather than rounded, matching what .smallest(..) does, and it is only printed when the smallest printed unit is s. .frac_sep(Some("_")) groups the digits in threes, which the 18 digit precisions need to stay readable.

Details

  • A year is 365.2425 days, which is exactly 31_556_952 seconds, so day counts run 0..=365 and arithmetic stays exact at second granularity. Override it with .secs_per_year(u64).
  • The _ appears only when both the date group and the time group are present.
  • Negative durations are prefixed with -. Zero carries no sign, so Dur::ZERO.neg() == Dur::ZERO.

Accepted input

Dur, core::time::Duration, u32, u64, i32, i64 as seconds and f32, f64 as seconds, through the ToDuration trait. Dur has const constructors from_secs, from_millis, from_micros, from_nanos, from_picos, from_femtos, from_attos and from_parts, plus from_secs_f64 and neg.

Formatting in tables

Both formatters return Display values that render through Formatter::pad, so width, alignment and fill work as usual and nothing is allocated on the way:

use humanize_proper::{bin, dur};

for (name, size, age) in [("index.db", 1_048_576, 90), ("wal.log", 6_291_456, 3_600)] {
    println!("{name:<10}{:>9}{:>11}", bin(size), dur(age));
}
// index.db       1MiB     01m30s
// wal.log        6MiB  01h00m00s

Scope

Deliberately out of scope: localization such as a decimal comma or grouped integer digits, and parsing, since this library only formats.

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Authorship

This project, including its purpose and overall architecture, was conceived and designed by its human authors. The implementation was generated in full with AI assistance (Claude Code), under the human authors' direction.