¿Cómo analizo una cadena en un número con Dart?

Resuelto Seth Ladd asked hace 11 años • 13 respuestas

Me gustaría analizar cadenas como 1o 32.23en números enteros y dobles. ¿Cómo puedo hacer esto con Dart?

Seth Ladd avatar Nov 01 '12 04:11 Seth Ladd
Aceptado

Puedes analizar una cadena en un número entero con int.parse(). Por ejemplo:

var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345

Tenga en cuenta que int.parse()acepta 0xcadenas con prefijo. De lo contrario, la entrada se trata como base-10.

Puedes analizar una cadena en un doble con double.parse(). Por ejemplo:

var myDouble = double.parse('123.45');
assert(myDouble is double);
print(myDouble); // 123.45

parse()lanzará FormatException si no puede analizar la entrada.

Seth Ladd avatar Oct 31 '2012 21:10 Seth Ladd

En Dart 2 int.tryParse está disponible.

Devuelve nulo para entradas no válidas en lugar de arrojar. Puedes usarlo así:

int val = int.tryParse(text) ?? defaultValue;
kgiannakakis avatar Apr 16 '2018 13:04 kgiannakakis

Según dardo 2.6

onErrorEl parámetro opcional de int.parseestá en desuso . Por lo tanto, deberías utilizar int.tryParseen su lugar.

Nota : Lo mismo se aplica a double.parse. Por lo tanto, utilice double.tryParseen su lugar.

  /**
   * ...
   *
   * The [onError] parameter is deprecated and will be removed.
   * Instead of `int.parse(string, onError: (string) => ...)`,
   * you should use `int.tryParse(string) ?? (...)`.
   *
   * ...
   */
  external static int parse(String source, {int radix, @deprecated int onError(String source)});

La diferencia es que int.tryParseregresa nullsi la cadena fuente no es válida.

  /**
   * Parse [source] as a, possibly signed, integer literal and return its value.
   *
   * Like [parse] except that this function returns `null` where a
   * similar call to [parse] would throw a [FormatException],
   * and the [source] must still not be `null`.
   */
  external static int tryParse(String source, {int radix});

Entonces, en tu caso debería verse así:

// Valid source value
int parsedValue1 = int.tryParse('12345');
print(parsedValue1); // 12345

// Error handling
int parsedValue2 = int.tryParse('');
if (parsedValue2 == null) {
  print(parsedValue2); // null
  //
  // handle the error here ...
  //
}
Ilker Cat avatar Apr 14 '2020 17:04 Ilker Cat

Las soluciones anteriores no funcionarán para Stringcasos como:

String str = '123 km';

Entonces, la respuesta en una sola línea, que me funciona en cada situación, será:

int r = int.tryParse(str.replaceAll(RegExp(r'[^0-9]'), '')) ?? defaultValue;
or
int? r = int.tryParse(str.replaceAll(RegExp(r'[^0-9]'), ''));

Pero tenga en cuenta que no funcionará para el siguiente tipo de cadena

String problemString = 'I am a fraction 123.45';
String moreProblem = '20 and 30 is friend';

Si desea extraer el doble, que funcionará en todos los tipos, utilice:

double d = double.tryParse(str.replaceAll(RegExp(r'[^0-9\.]'), '')) ?? defaultValue;
or
double? d = double.tryParse(str.replaceAll(RegExp(r'[^0-9\.]'), ''));

Esto funcionará problemStringpero no para moreProblem.

Zihan avatar Jun 27 '2021 05:06 Zihan