Is there a way to set the width parameter in println! with a variable?

Viewed 265

In C you can use set printf's width parameter dynamically like this:

printf("%*.*f", width, precision, value);

This is how I would like it to work:

let width = 8;
let precision = 2;
let value = 1234.56789;
println!("{:*.*}", width, precision, value);

But using that syntax throws expected '}' in format string.

This kind of works:

let width = 8;
let precision = 2;
let value = 1234.56789;
println!("{:8.*}", precision, value);

But as you can see the width is not set dynamically. I assume it doesn't work because of some good reason. Is it possible to make it work in a similar way or are there any workarounds?

1 Answers

You can write:

fn main() {
    let width = 8;
    let precision = 2;
    let value = 1234.56789;
    println!("{:width$.precision$}", value);
}

This avoids mixing the actual values to be formatted with the formatting parameters, which I think is nice.

You can also write:

fn main() {
    let width = 8;
    let precision = 2;
    let value = 1234.56789;
    println!("{:1$.2$}", value, width, precision);
}

Or:

fn main() {
    let width = 8;
    let precision = 2;
    let value = 1234.56789;
    println!("{:foo$.bar$}", value, foo = width, bar = precision);
}
Related