Format with const size?

I have simple function, to convert 12.3 to "0123":

fn format_number(x: f64) -> String {
    let mut out = format!("{:0>5.1}", x);
    out.remove(out.len() - 1 - 1);

all works fine, but I need to create the similar functions for cases where 2 digits in integer part and 2 digits in fraction part.

The first obvious idea is

fn format_number<const INT: usize, const FRAC: usize>(x: f64) -> String {
    let mut out = format!("{:0>INT + FRAC + 1.FRAC}", x);
    out.remove(out.len() - 1 - 1);

to call it like format_number::<3, 1>(number) and format_number::<2, 2>(number).

But obviously such code doesn't compile,
any idea how can I generate format string during compile time?

I'm unclear on exactly what the desired relationship between the parameters and the output is. But the width and precision format specifiers can be supplied as named[1] parameters to format!.

So here are a few possible solutions. If my guesses as to what exactly you wanted were off, perhaps you can adjust them to match. In particular, I didn't consider negative numbers at all.

  1. or positional, but that's more confusing IMO ↩ī¸Ž


Thanks, the way to specify width and precision from const/variable is what I want.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.