diff options
author | Louis Pilfold <louis@lpil.uk> | 2021-08-06 10:35:09 +0100 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2021-08-06 10:35:09 +0100 |
commit | 4bc5ec9bcca768c52b07b7398b385a574d0a6b15 (patch) | |
tree | a81e935912f439c4a6a0d62b07c0d34ff18cfcff /src | |
parent | 8ef4b3b7cb02674b06a6f172ce83697a158e53ac (diff) | |
download | gleam_stdlib-4bc5ec9bcca768c52b07b7398b385a574d0a6b15.tar.gz gleam_stdlib-4bc5ec9bcca768c52b07b7398b385a574d0a6b15.zip |
float.parse
Diffstat (limited to 'src')
-rw-r--r-- | src/gleam/float.gleam | 35 | ||||
-rw-r--r-- | src/gleam_stdlib.js | 10 |
2 files changed, 33 insertions, 12 deletions
diff --git a/src/gleam/float.gleam b/src/gleam/float.gleam index 857b593..b3f0df2 100644 --- a/src/gleam/float.gleam +++ b/src/gleam/float.gleam @@ -2,20 +2,33 @@ import gleam/order.{Order} if erlang { import gleam/string_builder +} - /// Attempts to parse a string as a float, returning `Error(Nil)` if it was not - /// possible. - /// - /// ## Examples - /// > parse("2.3") - /// Ok(2.3) - /// - /// > parse("ABC") - /// Error(Nil) - /// - pub external fn parse(String) -> Result(Float, Nil) = +/// Attempts to parse a string as a float, returning `Error(Nil)` if it was not +/// possible. +/// +/// ## Examples +/// > parse("2.3") +/// Ok(2.3) +/// +/// > parse("ABC") +/// Error(Nil) +/// +pub fn parse(string: String) -> Result(Float, Nil) { + do_parse(string) +} + +if erlang { + external fn do_parse(String) -> Result(Float, Nil) = "gleam_stdlib" "parse_float" +} + +if javascript { + external fn do_parse(String) -> Result(Float, Nil) = + "../gleam_stdlib.js" "parse_float" +} +if erlang { /// Returns the string representation of the provided float. /// /// ## Examples diff --git a/src/gleam_stdlib.js b/src/gleam_stdlib.js index 1e93901..a60b361 100644 --- a/src/gleam_stdlib.js +++ b/src/gleam_stdlib.js @@ -22,7 +22,15 @@ export function identity(x) { export function parse_int(value) { if (/^[-+]?(\d+)$/.test(value)) { - return gleam_ok(Number(value)); + return gleam_ok(parseInt(value)); + } else { + return gleam_error(Nil); + } +} + +export function parse_float(value) { + if (/^[-+]?(\d+)\.(\d+)$/.test(value)) { + return gleam_ok(parseFloat(value)); } else { return gleam_error(Nil); } |