6

I'm new to Rust and completely lost in the standard library. I do not want to add a crate just for padding. How do I pad left a number with zeroes up to a certain width?

Lets say I have this code and I need the pad_left implementation.

fn main() {
  let i = 5.to_string();

  let padded_i = pad_left(i, 2);
}
ditoslav
  • 4,563
  • 10
  • 47
  • 79

1 Answers1

3

The Rust Docs has an example of how you could format a number as a string with leading zeroes up to a certain width (5 in this example):

format!("Hello {:05}!", 5); // returns, "Hello 00005!"
format!("Hello {:05}!", -5); // returns, "Hello -0005!"

If you need to print the number, then you can replace the format! macro with print! or println! instead.

Brent Pappas
  • 392
  • 3
  • 11