humfmt 0.5.1

Ergonomic human-readable formatting toolkit for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use crate::locale::{English, Locale};
use crate::RoundingMode;

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum Precision {
    Decimals(u8),
    Significant(u8),
}

/// Builder-style configuration for compact number formatting.
///
/// # Quick reference
///
/// | Method | Default | Effect |
/// |---|---|---|
/// | [`precision(n)`] | `1` | Decimal places for the scaled fractional part |
/// | [`significant_digits(n)`] | `none` | Total significant digits (overrides precision) |
/// | [`compact(bool)`] | `true` | `"1500"` → `"1.5K"` vs `"1500"` |
/// | [`force_sign(bool)`] | `false` | `1500` → `"+1.5K"` |
/// | [`rounding(mode)`] | `HalfUp` | HalfUp, Floor, Ceil behaviour |
/// | [`long_units()`] | `false` | `"15.3K"` → `"15.3 thousand"` |
/// | [`separators(bool)`] | `false` | `"1234"` → `"1,234"` (when unscaled or uncompacted) |
/// | [`fixed_precision(bool)`] | `false` | `"1.5K"` → `"1.50K"` |
/// | [`locale(L)`] | `English` | Separators, suffixes, inflection rules |
///
/// [`precision(n)`]: NumberOptions::precision
/// [`significant_digits(n)`]: NumberOptions::significant_digits
/// [`compact(bool)`]: NumberOptions::compact
/// [`force_sign(bool)`]: NumberOptions::force_sign
/// [`rounding(mode)`]: NumberOptions::rounding
/// [`long_units()`]: NumberOptions::long_units
/// [`separators(bool)`]: NumberOptions::separators
/// [`fixed_precision(bool)`]: NumberOptions::fixed_precision
/// [`locale(L)`]: NumberOptions::locale
///
/// # Examples
///
/// ```rust
/// use humfmt::NumberOptions;
///
/// let opts = NumberOptions::new()
///     .precision(2)
///     .long_units();
///
/// assert_eq!(humfmt::number_with(15_320, opts).to_string(), "15.32 thousand");
/// ```
#[derive(Copy, Clone, Debug)]
pub struct NumberOptions<L: Locale = English> {
    pub(crate) precision: Precision,
    pub(crate) compact: bool,
    pub(crate) force_sign: bool,
    pub(crate) rounding: RoundingMode,
    pub(crate) long_units: bool,
    pub(crate) separators: bool,
    pub(crate) fixed_precision: bool,
    pub(crate) locale: L,
}

impl NumberOptions<English> {
    /// Creates default English formatting options.
    ///
    /// | Option | Default |
    /// |---|---|
    /// | precision | `1` |
    /// | compact | `true` |
    /// | force sign | `false` |
    /// | rounding | `HalfUp` |
    /// | long units | `false` (short suffixes: `K`, `M`, …) |
    /// | separators | `false` (no digit grouping) |
    /// | fixed precision | `false` (trailing zeros trimmed) |
    /// | locale | `English` |
    #[inline]
    pub fn new() -> Self {
        Self {
            precision: Precision::Decimals(1),
            compact: true,
            force_sign: false,
            rounding: RoundingMode::HalfUp,
            long_units: false,
            separators: false,
            fixed_precision: false,
            locale: English,
        }
    }
}

impl<L: Locale> Default for NumberOptions<L> {
    #[inline]
    fn default() -> Self {
        Self {
            precision: Precision::Decimals(1),
            compact: true,
            force_sign: false,
            rounding: RoundingMode::HalfUp,
            long_units: false,
            separators: false,
            fixed_precision: false,
            locale: L::default(),
        }
    }
}

impl<L: Locale> NumberOptions<L> {
    /// Sets the number of decimal places shown in the scaled fractional part.
    ///
    /// Precision is clamped to `0..=6`.
    ///
    /// Trailing zeros are trimmed by default. Use [`fixed_precision(true)`] to
    /// keep them for consistent column widths.
    ///
    /// [`fixed_precision(true)`]: NumberOptions::fixed_precision
    ///
    /// # Behaviour table
    ///
    /// | Input | `precision(0)` | `precision(1)` (default) | `precision(2)` |
    /// |---:|---|---|---|
    /// | `1_400` | `"1K"` | `"1.4K"` | `"1.4K"` (trimmed) |
    /// | `1_500` | `"2K"` | `"1.5K"` | `"1.5K"` (trimmed) |
    /// | `15_320` | `"15K"` | `"15.3K"` | `"15.32K"` |
    /// | `999_950` | `"1M"` | `"1M"` | `"1M"` (rescaled after rounding) |
    ///
    /// # Examples
    ///
    /// ```rust
    /// use humfmt::NumberOptions;
    ///
    /// assert_eq!(humfmt::number_with(15_320, NumberOptions::new().precision(0)).to_string(), "15K");
    /// assert_eq!(humfmt::number_with(15_320, NumberOptions::new().precision(2)).to_string(), "15.32K");
    /// ```
    #[inline]
    pub fn precision(mut self, n: u8) -> Self {
        self.precision = Precision::Decimals(n.min(6));
        self
    }

    /// Sets the total number of significant digits to display.
    ///
    /// This provides an alternative to fixed decimal places, ensuring that the
    /// output always maintains a stable level of precision regardless of magnitude.
    ///
    /// Clamped to `1..=39` (the maximum digits in a `u128`).
    ///
    /// # Behaviour table
    ///
    /// | Input | `significant_digits(3)` | Notes |
    /// |---:|---|---|
    /// | `1_234` | `"1.23K"` | `1`, `2`, `3` are the 3 significant digits |
    /// | `12_345` | `"12.3K"` | `1`, `2`, `3` are the 3 significant digits |
    /// | `123_456` | `"123K"` | `1`, `2`, `3` are the 3 significant digits |
    /// | `1_234` (unscaled) | `"1230"` | Unscaled integer is rounded directly |
    ///
    /// With `fixed_precision(true)`, trailing zeros are padded to fill the
    /// significant digit count:
    ///
    /// | Input | `significant_digits(3)` + `fixed_precision` |
    /// |---:|---|
    /// | `1` | `"1.00"` |
    /// | `10` | `"10.0"` |
    /// | `100` | `"100"` |
    ///
    /// # Examples
    ///
    /// ```rust
    /// use humfmt::NumberOptions;
    ///
    /// let opts = NumberOptions::new().significant_digits(3);
    /// assert_eq!(humfmt::number_with(1234, opts).to_string(), "1.23K");
    /// assert_eq!(humfmt::number_with(12345, opts).to_string(), "12.3K");
    /// ```
    #[inline]
    pub fn significant_digits(mut self, n: u8) -> Self {
        self.precision = Precision::Significant(n.clamp(1, 39));
        self
    }

    /// Controls whether the number should be compacted using magnitude suffixes (e.g. `K`, `M`).
    ///
    /// - `true` (default): Values >= 1,000 are compacted (`1500` → `"1.5K"`).
    /// - `false`: Values are rendered fully unscaled (`1500` → `"1500"`).
    ///
    /// Disabling compaction is extremely useful when combined with [`separators(true)`]
    /// to output fully formatted large numbers like `"1,234,567"`.
    ///
    /// [`separators(true)`]: NumberOptions::separators
    ///
    /// # Behaviour table
    ///
    /// | Input | `compact(true)` (default) | `compact(false)` |
    /// |---:|---|---|
    /// | `999` | `"999"` | `"999"` |
    /// | `1500` | `"1.5K"` | `"1500"` |
    /// | `1_500_000` | `"1.5M"` | `"1500000"` |
    /// | `1_500_000.5` (f64) | `"1.5M"` | `"1500000.5"` |
    ///
    /// # Examples
    ///
    /// ```rust
    /// use humfmt::NumberOptions;
    ///
    /// let opts = NumberOptions::new().compact(false).separators(true);
    /// assert_eq!(humfmt::number_with(1_234_567, opts).to_string(), "1,234,567");
    /// ```
    #[inline]
    pub fn compact(mut self, enabled: bool) -> Self {
        self.compact = enabled;
        self
    }

    /// Forces the output of a `+` sign for strictly positive values.
    ///
    /// Values that round to exactly zero will output `0` without a sign.
    /// Useful for deltas and change indicators.
    ///
    /// # Behaviour table
    ///
    /// | Input | `force_sign(false)` (default) | `force_sign(true)` |
    /// |---:|---|---|
    /// | `1500` | `"1.5K"` | `"+1.5K"` |
    /// | `42` | `"42"` | `"+42"` |
    /// | `0` | `"0"` | `"0"` (no sign on zero) |
    /// | `-1500` | `"-1.5K"` | `"-1.5K"` (negatives unchanged) |
    /// | `0.004` (f64, rounds to 0) | `"0"` | `"0"` (no sign on rounded-zero) |
    ///
    /// # Examples
    ///
    /// ```rust
    /// use humfmt::NumberOptions;
    ///
    /// let opts = NumberOptions::new().force_sign(true);
    /// assert_eq!(humfmt::number_with(1500, opts).to_string(), "+1.5K");
    /// assert_eq!(humfmt::number_with(-1500, opts).to_string(), "-1.5K");
    /// assert_eq!(humfmt::number_with(0, opts).to_string(), "0");
    /// ```
    #[inline]
    pub fn force_sign(mut self, yes: bool) -> Self {
        self.force_sign = yes;
        self
    }

    /// Sets the rounding direction for values that require precision cutoff.
    ///
    /// - `HalfUp` (default): standard mathematical rounding. Ties round away from zero.
    /// - `Floor`: always round towards negative infinity.
    /// - `Ceil`: always round towards positive infinity.
    ///
    /// Rounding may rescale across a suffix boundary. For example, `999_500`
    /// at `precision(0)` with `HalfUp` rounds to `1000K` which rescales to `1M`.
    ///
    /// # Behaviour table
    ///
    /// | Input | `precision(0)` + `HalfUp` | `Floor` | `Ceil` |
    /// |---:|---|---|---|
    /// | `1_100` | `"1K"` | `"1K"` | `"2K"` |
    /// | `1_500` | `"2K"` | `"1K"` | `"2K"` |
    /// | `1_900` | `"2K"` | `"1K"` | `"2K"` |
    /// | `999_500` | `"1M"` (rescaled) | `"999K"` | `"1M"` (rescaled) |
    /// | `-1_500` | `"-2K"` | `"-2K"` | `"-1K"` |
    ///
    /// # Examples
    ///
    /// ```rust
    /// use humfmt::{NumberOptions, RoundingMode};
    ///
    /// let floor = NumberOptions::new().precision(0).rounding(RoundingMode::Floor);
    /// assert_eq!(humfmt::number_with(1_900, floor).to_string(), "1K");
    ///
    /// let ceil = NumberOptions::new().precision(0).rounding(RoundingMode::Ceil);
    /// assert_eq!(humfmt::number_with(1_100, ceil).to_string(), "2K");
    /// ```
    #[inline]
    pub fn rounding(mut self, mode: RoundingMode) -> Self {
        self.rounding = mode;
        self
    }

    /// Uses long-form suffix labels instead of short ones.
    ///
    /// Long suffixes come from the active locale. For English:
    /// `"K"` → `" thousand"`, `"M"` → `" million"`, and so on.
    ///
    /// For non-English locales, long suffixes may also be inflected based on
    /// the rendered value (e.g. Russian: `"2 тысячи"`, `"5 тысяч"`).
    ///
    /// # Behaviour table
    ///
    /// | Input | Short (default) | Long |
    /// |---:|---|---|
    /// | `999` | `"999"` | `"999"` |
    /// | `1_000` | `"1K"` | `"1 thousand"` |
    /// | `1_500` | `"1.5K"` | `"1.5 thousand"` |
    /// | `1_000_000` | `"1M"` | `"1 million"` |
    ///
    /// # Examples
    ///
    /// ```rust
    /// use humfmt::NumberOptions;
    ///
    /// assert_eq!(humfmt::number_with(15_320, NumberOptions::new().long_units()).to_string(), "15.3 thousand");
    /// assert_eq!(humfmt::number_with(1_000_000, NumberOptions::new().long_units()).to_string(), "1 million");
    /// ```
    #[inline]
    pub fn long_units(mut self) -> Self {
        self.long_units = true;
        self
    }

    /// Enables digit grouping separators for unscaled output.
    ///
    /// **Important:** grouping separators apply **only when the value is not
    /// compacted** — that is, when the output has no suffix.
    /// For compacted output like `"15.3K"` the integer part is always small
    /// (`15`) and grouping would never trigger anyway.
    ///
    /// To show grouped digits for large numbers, you should disable compact scaling
    /// via [`compact(false)`].
    ///
    /// [`compact(false)`]: NumberOptions::compact
    ///
    /// Separator characters come from the active locale:
    /// - English: group separator `','`, decimal separator `'.'`
    /// - Russian / Polish: group separator `' '`, decimal separator `','`
    ///
    /// # Behaviour table
    ///
    /// | Input | `separators(false)` | `separators(true)` |
    /// |---:|---|---|
    /// | `999` | `"999"` | `"999"` |
    /// | `1_234` | `"1.2K"` | `"1.2K"` (compacted, grouping has no effect) |
    /// | `1_234` with `compact(false)` | `"1234"` | `"1,234"` |
    /// | `1_234_567` with `compact(false)`| `"1234567"` | `"1,234,567"` |
    /// | `-1_234_567` with `compact(false)`| `"-1234567"` | `"-1,234,567"` |
    ///
    /// # Examples
    ///
    /// ```rust
    /// use humfmt::{number_with, NumberOptions};
    ///
    /// // Disable compact scaling to show grouped digits.
    /// let opts = NumberOptions::new().compact(false).separators(true);
    /// assert_eq!(number_with(1_234_567, opts).to_string(), "1,234,567");
    /// ```
    #[inline]
    pub fn separators(mut self, yes: bool) -> Self {
        self.separators = yes;
        self
    }

    /// Controls whether trailing fractional zeros are preserved.
    ///
    /// - `false` (default): trailing zeros are trimmed — `"1.50K"` → `"1.5K"`
    /// - `true`: trailing zeros are kept — `"1.50K"` stays `"1.50K"`
    ///
    /// Useful for consistent column widths in tables, logs, and dashboards.
    ///
    /// # Behaviour table
    ///
    /// | Input | `precision(2)` trimmed | `precision(2)` fixed |
    /// |---:|---|---|
    /// | `1_000` | `"1K"` | `"1.00K"` |
    /// | `1_500` | `"1.5K"` | `"1.50K"` |
    /// | `1_540` | `"1.54K"` | `"1.54K"` |
    /// | `1_000_000` | `"1M"` | `"1.00M"` |
    ///
    /// # Examples
    ///
    /// ```rust
    /// use humfmt::NumberOptions;
    ///
    /// let trimmed = NumberOptions::new().precision(2);
    /// assert_eq!(humfmt::number_with(1_500, trimmed).to_string(), "1.5K");
    /// assert_eq!(humfmt::number_with(1_000, trimmed).to_string(), "1K");
    ///
    /// let fixed = NumberOptions::new().precision(2).fixed_precision(true);
    /// assert_eq!(humfmt::number_with(1_500, fixed).to_string(), "1.50K");
    /// assert_eq!(humfmt::number_with(1_000, fixed).to_string(), "1.00K");
    /// ```
    #[inline]
    pub fn fixed_precision(mut self, yes: bool) -> Self {
        self.fixed_precision = yes;
        self
    }

    /// Switches the active locale.
    ///
    /// Locale affects:
    /// - decimal and grouping separator characters
    /// - compact suffix labels (short and long)
    /// - suffix inflection rules (Russian, Polish)
    /// - maximum compact scaling index
    ///
    /// # Examples
    ///
    /// ```rust
    /// use humfmt::{number_with, NumberOptions};
    /// use humfmt::locale::English;
    ///
    /// assert_eq!(number_with(15_320, NumberOptions::new().locale(English)).to_string(), "15.3K");
    /// ```
    #[inline]
    pub fn locale<N: Locale>(self, locale: N) -> NumberOptions<N> {
        NumberOptions {
            precision: self.precision,
            compact: self.compact,
            force_sign: self.force_sign,
            rounding: self.rounding,
            long_units: self.long_units,
            separators: self.separators,
            fixed_precision: self.fixed_precision,
            locale,
        }
    }
}