有没有一种简单的方法和动态的方法来格式化字符串中的数字以供人类阅读?例如10000000000
变成10,000,000,000
. 我已经看到了这个问题,但是答案已经过时且损坏了(带有示例的答案)。
问问题
1264 次
3 回答
4
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
于 2016-01-11T03:59:55.317 回答
3
我从来没有在我的生活中使用过 rust ,但这是我通过从这里翻译一个解决方案想出的:
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);
}
返回“-117,608,854”
于 2016-01-11T04:33:39.240 回答
2
对于我的语言环境,这似乎有效!可能不是最惯用的锈,但它是功能性的。
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);
}
于 2016-01-11T04:28:56.363 回答