rustc_data_structures/thousands/mod.rs
1//! This is a bare-bones alternative to the `thousands` crate on crates.io, for
2//! printing large numbers in a readable fashion.
3
4#[cfg(test)]
5mod tests;
6
7fn format_with_underscores(mut s: String) -> String {
8 // Ignore a leading '-'.
9 let start = if s.starts_with('-') { 1 } else { 0 };
10
11 // Stop after the first non-digit, e.g. '.' or 'e' for floats.
12 let non_digit = s[start..].find(|c: char| !c.is_digit(10));
13 let end = if let Some(non_digit) = non_digit { start + non_digit } else { s.len() };
14
15 // Insert underscores within `start..end`.
16 let mut i = end;
17 while i > start + 3 {
18 i -= 3;
19 s.insert(i, '_');
20 }
21 s
22}
23
24/// Print a `usize` with underscore separators.
25pub fn usize_with_underscores(n: usize) -> String {
26 format_with_underscores(format!("{n}"))
27}
28
29/// Print an `isize` with underscore separators.
30pub fn isize_with_underscores(n: isize) -> String {
31 format_with_underscores(format!("{n}"))
32}
33
34/// Print an `f64` with precision 1 (one decimal place) and underscore separators.
35pub fn f64p1_with_underscores(n: f64) -> String {
36 format_with_underscores(format!("{n:.1}"))
37}