Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the formatter's decimal separator in Rust?

The function below results in "10.000". Where I live this means "ten thousand".

format!("{:.3}", 10.0);

I would like the output to be "10,000".

like image 556
roeland Avatar asked Jun 15 '17 20:06

roeland


People also ask

What is the correct decimal separator?

In the United States, we use the decimal or period (“.”) to represent the difference between whole numbers and partial numbers. We use the comma (“,”) to separate groups of three places on the whole numbers side. This might be different from the way you currently write numbers.

What is format macro in Rust?

Macro std::formatCreates a String using interpolation of runtime expressions. The first argument format! receives is a format string. This must be a string literal. The power of the formatting string is in the {} s contained.


1 Answers

Since the standard library doesn't have this functionality (localization of number format), you can just replace the dot with a comma:

fn main() {
    println!("{}", format!("{:.3}", 10.0).replacen(".", ",", 1));
}

There are other ways of doing this, but this is probably the most straightforward solution.

like image 152
ljedrz Avatar answered Sep 19 '22 22:09

ljedrz