首页 > 解决方案 > How to convert f32 to String with dynamic precision?

问题描述

In my rust code I have a function which takes a float and precision as args. The function should return the formatted string. However, I am not sure how I can format with dynamic precision,

fn convert(val: f32, precision: i16) -> String {
    format!("{:.2}", val) // The 2 should be replaced with precision
}
// convert(1.2345, 1) -> 1.2
// convert(1.2345, 2) -> 1.23

标签: rust

解决方案


According to the documentation:

There are three possible ways to specify the desired precision:

  1. An integer .N:

    the integer N itself is the precision.

  2. An integer or name followed by dollar sign .N$:

    use format argument N (which must be a usize) as the precision.

  3. An asterisk .*:

    .* means that this {...} is associated with two format inputs rather than one: the first input holds the usize precision, and the second holds the value to print. Note that in this case, if one uses the format string {<arg>:<spec>.*}, then the <arg> part refers to the value to print, and the precision must come in the input preceding <arg>.

That is, you can use:

fn convert(val: f32, precision: usize) -> String {
    format!("{:.prec$}", val, prec = precision)
}

fn main() {
    println!("{}", convert(3.14, 0));
    println!("{}", convert(3.14, 1));
    println!("{}", convert(3.14, 2));
    println!("{}", convert(3.14, 3));
}

(Permalink to the playground)


推荐阅读