Formater une chaine de caracteres

chakall Messages postés 5 Date d'inscription mardi 21 janvier 2003 Statut Membre Dernière intervention 18 mars 2003 - 18 mars 2003 à 14:08
willowman Messages postés 143 Date d'inscription vendredi 5 juillet 2002 Statut Membre Dernière intervention 18 mars 2006 - 19 mars 2003 à 01:06
:) salut
j'ai un entier compris entre 1 et 900 et je veux le transformer en une chaine de " quatre " caracteres avec des zéros devant.
ex: 1 devient "0001",24 devient "0024", 458 devient "0458" etc...
comment faire, quelle fonction utiliser?
merci à tous

1 réponse

willowman Messages postés 143 Date d'inscription vendredi 5 juillet 2002 Statut Membre Dernière intervention 18 mars 2006 1
19 mars 2003 à 01:06
Salut !

Voici un moyen d'arriver a tes fins :

/* la methode convertie int en String $$$$ */

public static String intToString(int val) {
String chaine = (new Integer(val)).toString();
String result = new String();

for(int i=4;i>chaine.length();i--)
result = result.concat("0");

return result = result.concat(chaine);
}

/* exemple d'utilisation */
public static void main(String[] args) {

int i=13;
System.out.println(intToString(i)); /* donne 13 en 0013 */
i=4;
System.out.println(intToString(i)); /* 4 en 0004 */
i=608;
System.out.println(intToString(i)); /* 608 en 0608 */
i=900;
System.out.println(intToString(i)); /* 900 en 0900 */

}

Allez, a pluche ;-)
0
Rejoignez-nous