J’ai “1” en tant que chaîne et j’aimerais la convertir en décimal, 1
, en entier.
J’ai essayé charAt()
, mais il retourne 49, pas 1 entier.
Alors, que faut-il pour convertir la chaîne “1” en 1 entier?
Utilisez la classe Wrapper.
Des exemples sont ci-dessous
int
int a = Integer.parseInt("1"); // Outputs 1
flotte
float a = Float.parseFloat("1"); // Outputs 1.0
double
double a = Double.parseDouble("1"); // Outputs 1.0
longue
long a = Long.parseLong("1"); // Outputs 1
int one = Integer.parseInt("1");
Idéalement, vous devriez également détecter les erreurs:
int i; Ssortingng s = "might not be a number"; try { i = Integer.parseInt(s); } catch (NumberFormatException e) { //do something }
Integer.parseInt
fait exactement cela.
int foo = Integer.parseInt("1");
int foo = Integer.parseInt("1"); //foo now equals 1
Ssortingng s = "1"; int i = Integer.valueOf(s);