String Problem

Hi All,

Can anyone tell me if java has a way to format a string to display in a certain way always. For instance i have

publicclass foo

{

publicstaticvoid main (String[] args)

{

String Number1="12345";

String Number2="123";

}

}

And i want both String when print to print with six digits and leading zeroes to fill in. For example Number1 would print 012345 and Number2 000123

Thanks for the help!

[793 byte] By [JoCa] at [2007-11-27 2:03:04]
# 1

use NumberFormat http://java.sun.com/j2se/1.4.2/docs/api/java/text/NumberFormat.html

import java.text.*;

public class foo

{

public static void main (String[] args)

{

String Number1="12345";

String Number2="123";

try{

double d = Double.parseDouble(Number1);

NumberFormat formatter = new DecimalFormat("000000");

String s = formatter.format(d);

System.out.println(s);

}catch(Exception e){

e.printStackTrace();

}

}

}

java_2006a at 2007-7-12 1:45:01 > top of Java-index,Java Essentials,Java Programming...
# 2

If I'm not mistaken, the leading zero's can only be added in from of numbers, not Strings (when using the printf(...) method):int number1 = 12345;

int number2 = 123;

System.out.printf("%06d\n%06d", number1, number2);

prometheuzza at 2007-7-12 1:45:01 > top of Java-index,Java Essentials,Java Programming...
# 3
Use the "format" method available in StringString.format(String format, Object... args)
SirGenerala at 2007-7-12 1:45:01 > top of Java-index,Java Essentials,Java Programming...
# 4
The method java_2006 posted will work fine.
abillconsla at 2007-7-12 1:45:02 > top of Java-index,Java Essentials,Java Programming...