Skip to content

Commit c225099

Browse files
committed
Merge: Extend is_numeric to support negative values and scientific notation
Pull-Request: #1917 Reviewed-by: Lucas Bajolet <r4pass@hotmail.com> Reviewed-by: Jean Privat <jean@pryen.org>
2 parents 5380a23 + 8cda69c commit c225099

File tree

3 files changed

+14
-8
lines changed

3 files changed

+14
-8
lines changed

lib/core/text/abstract_text.nit

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -305,26 +305,32 @@ abstract class Text
305305
end
306306
end
307307

308-
# Returns `true` if the string contains only Numeric values (and one "," or one "." character)
308+
# Is this string in a valid numeric format compatible with `to_f`?
309309
#
310310
# assert "123".is_numeric == true
311311
# assert "1.2".is_numeric == true
312-
# assert "1,2".is_numeric == true
312+
# assert "-1.2".is_numeric == true
313+
# assert "-1.23e-2".is_numeric == true
313314
# assert "1..2".is_numeric == false
315+
# assert "".is_numeric == false
314316
fun is_numeric: Bool
315317
do
316-
var has_point_or_comma = false
318+
var has_point = false
319+
var e_index = -1
317320
for i in [0..length[ do
318321
var c = chars[i]
319322
if not c.is_numeric then
320-
if (c == '.' or c == ',') and not has_point_or_comma then
321-
has_point_or_comma = true
323+
if c == '.' and not has_point then
324+
has_point = true
325+
else if c == 'e' and e_index == -1 and i > 0 and i < length - 1 and chars[i-1] != '-' then
326+
e_index = i
327+
else if c == '-' and i == e_index + 1 and i < length - 1 then
322328
else
323329
return false
324330
end
325331
end
326332
end
327-
return true
333+
return not is_empty
328334
end
329335

330336
# Returns `true` if the string contains only Hex chars

tests/sav/test_string_is_numeric.res

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
false
22
true
33
true
4-
true
4+
false
55
false
66
false
77
false

tests/test_string_is_numeric.nit

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ print "45".is_numeric
2525
#True
2626
print "45.3".is_numeric
2727

28-
#True
28+
#False
2929
print "45,3".is_numeric
3030

3131
#False

0 commit comments

Comments
 (0)