Filling to get a certain number of digits in a number

String val = "98"

I need to get the output as 0000098(7 digits).

I need to leave in writing zeros in a string or integer value ...

The number stored in val is dynamic and can contain any number of digits, but the output should always be 7 digits.

+5
source share
4 answers

In groovy, you can insert lines like this:

val.padLeft( 7, '0' )

This will put the left side of the string with zeros until it becomes 7 characters long

+17
source

Use String.format:

public class A {
  public static void main(String[] args) {
    System.out.println(String.format("%07d", 98)); // -> 0000098
  }
}
+10
source

String NumberFormat :

NumberFormat formatter = new DecimalFormat("0000000");

This means your string will be filled with zeros as you want.

And then, to get the string format, you can do:

String formatRes = formatter.format(new Double(val));

because the "format" method requires a double argument.

0
source

All Articles