7

Is there an easy way and dynamic way to format numbers in a string to be human readable? For example turn 10000000000 into 10,000,000,000. I have seen this question but the answers are outdated and broken (the one with the example).

Community
  • 1
  • 1
Jared Mackey
  • 3,998
  • 4
  • 31
  • 50

3 Answers3

5

Try this psuedo algorithm:

  1. Divide the string length by 3
  2. Round that down, and we'll call it x
  3. Loop over the string x times, going backwards:

    1. Get the string at x times 3 position, or index [(x times 3) - 1], we'll call it y.
    2. Replace y with "," + y
Quill
  • 2,729
  • 1
  • 33
  • 44
3

I've never used rust in my life but this is what I came up with by translating a solution from here:

fn main() {
    let i = -117608854;
    printcomma(i);
}

fn printcomma(mut i: i32) {
    if i < 0 {
        print!("-");
        i=-i;
    }
    if i < 1000 {
        print!("{}", i.to_string());
        return;
    }
    printcomma(i/1000);
    print!(",{:03}", i%1000);
}

returns "-117,608,854"

Community
  • 1
  • 1
2

For my locale this seemed to work! Probably isn't the most idiomatic rust, but it is functional.

fn readable(mut o_s: String) -> String {
    let mut s = String::new();
    let mut negative = false;
    let values: Vec<char> = o_s.chars().collect();
    if values[0] == '-' {
        o_s.remove(0);
        negative = true;
    }
    for (i ,char) in o_s.chars().rev().enumerate() {
        if i % 3 == 0 && i != 0 {
            s.insert(0, ',');
        }
        s.insert(0, char);
    }
    if negative {
        s.insert(0, '-');
    }
    return s
}

fn main() {
    let value: i64 = -100000000000;
    let new_value = readable(value.to_string());
    println!("{}", new_value);
}
Jared Mackey
  • 3,998
  • 4
  • 31
  • 50