aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorMainShayne233 <shaynetremblay@hotmail.com>2019-04-07 00:24:24 -0400
committerLouis Pilfold <louis@lpil.uk>2019-04-07 08:54:53 +0000
commit8cf56dae7043c25b152e10aa02d0a7ead7454380 (patch)
tree150e46aab0d7741e0eec8c7e31d80d658939366f /src
parent673e9e907093bd448db3b108b3d654c13cdc66f7 (diff)
downloadgleam_stdlib-8cf56dae7043c25b152e10aa02d0a7ead7454380.tar.gz
gleam_stdlib-8cf56dae7043c25b152e10aa02d0a7ead7454380.zip
Implement parse_float
Diffstat (limited to 'src')
-rw-r--r--src/gleam__stdlib.erl11
-rw-r--r--src/str.gleam28
2 files changed, 38 insertions, 1 deletions
diff --git a/src/gleam__stdlib.erl b/src/gleam__stdlib.erl
index 7ee4ba8..05623c6 100644
--- a/src/gleam__stdlib.erl
+++ b/src/gleam__stdlib.erl
@@ -6,7 +6,7 @@
atom_create_from_string/1, atom_to_string/1, map_fetch/2,
iodata_append/2, iodata_prepend/2, identity/1, decode_int/1,
decode_string/1, decode_bool/1, decode_float/1, decode_thunk/1,
- decode_tuple/1, decode_list/1, decode_field/2, parse_int/1]).
+ decode_tuple/1, decode_list/1, decode_field/2, parse_int/1, parse_float/1]).
expect_equal(Actual, Expected) -> ?assertEqual(Expected, Actual).
expect_not_equal(Actual, Expected) -> ?assertNotEqual(Expected, Actual).
@@ -78,3 +78,12 @@ parse_int(String) ->
_ ->
{error, parse_error}
end.
+
+parse_float(String) ->
+ case string:to_float(binary:bin_to_list(String)) of
+ {Float, []} ->
+ {ok, Float};
+
+ _ ->
+ {error, parse_error}
+ end.
diff --git a/src/str.gleam b/src/str.gleam
index 6ee8235..bd027a1 100644
--- a/src/str.gleam
+++ b/src/str.gleam
@@ -121,6 +121,34 @@ test parse_int {
|> expect:equal(_, Error(ParseError))
}
+pub external fn parse_float(String) -> Result(Float, ParseError) = "gleam__stdlib" "parse_float";
+
+test parse_float {
+ "1.23"
+ |> parse_float
+ |> expect:equal(_, Ok(1.23))
+
+ "5.0"
+ |> parse_float
+ |> expect:equal(_, Ok(5.0))
+
+ "0.123456789"
+ |> parse_float
+ |> expect:equal(_, Ok(0.123456789))
+
+ ""
+ |> parse_float
+ |> expect:equal(_, Error(ParseError))
+
+ "what"
+ |> parse_float
+ |> expect:equal(_, Error(ParseError))
+
+ "1"
+ |> parse_float
+ |> expect:equal(_, Error(ParseError))
+}
+
pub external fn base_from_int(Int, Int) -> String = "erlang" "integer_to_binary"
test base_from_int {