How to pad an integer with leading zeros in Java?
Hello everyone! I'm new to Java and came across a task that seems simple, but I can't find the right solution. I need to output an integer, for example, 42, but so that it always takes up, say, 5 characters, and the missing positions on the left are filled with zeros. That is, I want to get "00042". \n\nI tried using String.format(), but I don't quite understand how to set the specifier correctly. I tried writing something like `String.format("%5d", 42)`, but it adds spaces on the left, not zeros. It gives " 42". I also tried DecimalFormat, but there's some syntax with masks, and I got confused.\n\nHere's an example of my code:\n```java\nint number = 42;\nString padded = String.format("%5d", number);\nSystem.out.println(padded); // Outputs " 42", but I need "00042"\n```\n\nPlease advise.
No answers yet.
Log in to leave an answer