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).
Asked
Active
Viewed 1,899 times
7

Community
- 1
- 1

Jared Mackey
- 3,998
- 4
- 31
- 50
-
5http://stackoverflow.com/questions/26998485/rust-print-format-number-with-thousand-separator – Cecilio Pardo Jan 10 '16 at 23:07
3 Answers
5
Try this psuedo algorithm:
- Divide the string length by 3
- Round that down, and we'll call it
x
Loop over the string
x
times, going backwards:- Get the string at
x
times 3 position, or index [(x times 3) - 1], we'll call ity
. - Replace
y
with"," + y
- Get the string at

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

Dylan James McGannon
- 834
- 1
- 7
- 14
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
-
1This wont work for some negative numbers, try "-100000000" for example. – Dylan James McGannon Jan 11 '16 at 04:35
-
@DylanJamesMcGannon Thanks for pointing that out. I have resolved that issue. – Jared Mackey Jan 11 '16 at 05:28