Search code examples
rustrustup

Can't use anything but 0 to pad a number in println


I am new to Rust, hence I am experimenting with various argument when passing to println! macro. when I try the following code I can compile it successfully.

println! (" let the world be in peace {number:0width$} ",number = 1.1414, width = 9);

the out is as follows :

let the world be in peace 0001.1414

hence my understanding is based on value of width, the value of 0 is added as padding to output. But When I try the following code to add 1 as padding, it leads to a Compilation Error:

println! ("let me know {number:1width$}",number = 1.1414, width = 9); 

The Compilation Error stack is as follows:

    error: invalid format string: expected `'}'`, found `'$'`
  --> print_statements.rs:25:42
   |
25 |     println! ("let me know {number:1width$}",number = 1.1414, width = 9);
   |                            -             ^ expected `}` in format string
   |                            |
   |                            because of this opening brace
   |
   = note: if you intended to print `{`, you can escape it using `{{`

error: aborting due to previous error

Am I missing something? thanks for your help!


Solution

  • While the naming convention may unfortunately make it seem that 1width (or any number in front of width) is valid, this isn't true. The 0 is a specific number formatting flag for padding a number with 0 instead of spaces like normal.

    It may be helpful to think about the purpose of width for why this is the case. Width ensures a value takes up at least a specific number of characters (useful for aligning multiple lines) by filling up the remaining space with a filler character that does not change the value of what's printed. 0 is given as an additional choice versus spaces because adding 0s to the beginning/end of a number does not change the value, but adding 1s completely changes the printed value in a way that is unpredictable (based on the number length).

    That said, rust provides fill/alignment as a way to specify the character used as padding for width. Using that, your println! becomes the following:

    println!("let me know {number:1>width$}", number = 1.1414, width = 9);