The number of people read

Is there an easy way and a dynamic way to format numbers in a string so that they are readable? For example, turn 10000000000 to 10,000,000,000 . I saw this question, but the answers are outdated and broken (the one given in the example).

+5
source share
3 answers

For my locale, this seemed to work! This is probably not 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); } 
+2
source

Try this psuedo algorithm:

  • Divide the string length by 3
  • For the sake of this, and we will call it x
  • Scroll the line x times, go back:

    • Get the string at x times 3 position or index [(x times 3) - 1], we will call it y .
    • Replace y with "," + y
+4
source

I have never used rust in my life, but this is what I came up with when translating the 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"

+3
source

Source: https://habr.com/ru/post/1240293/


All Articles