Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(2081)

Unified Diff: sdk/lib/core/num.dart

Issue 85633003: Add num.parse. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Update status file for IE. Created 7 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « sdk/lib/core/int.dart ('k') | tests/corelib/corelib.status » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: sdk/lib/core/num.dart
diff --git a/sdk/lib/core/num.dart b/sdk/lib/core/num.dart
index 674ab2a469f22d96f265a20fdece0016e3bc52a7..c6bb4f85288833b2f71cf606633eb773d0d1b702 100644
--- a/sdk/lib/core/num.dart
+++ b/sdk/lib/core/num.dart
@@ -359,4 +359,33 @@ abstract class num implements Comparable<num> {
*
*/
String toString();
+
+ /**
+ * Parses a string containing a number literal into a number.
+ *
+ * The method first tries to read the [input] as integer (similar to
+ * [int.parse] without a radix).
+ * If that fails, it tries to parse the [input] as a double (similar to
+ * [double.parse]).
+ * If that fails, too, it invokes [onError] with [input].
+ *
+ * If no [onError] is supplied, it defaults to a function that throws a
+ * [FormatException].
+ *
+ * For any number `n`, this function satisfies
+ * `identical(n, num.parse(n.toString()))`.
+ */
+ static num parse(String input, [num onError(String input)]) {
+ String source = input.trim();
+ // TODO(lrn): Optimize to detect format and result type in one check.
+ num result = int.parse(source, onError: _returnNull);
+ if (result != null) return result;
+ result = double.parse(source, _returnNull);
+ if (result != null) return result;
+ if (onError == null) throw new FormatException(input);
+ return onError(input);
+ }
+
+ /** Helper function for [parse]. */
+ static _returnNull(_) => null;
}
« no previous file with comments | « sdk/lib/core/int.dart ('k') | tests/corelib/corelib.status » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698