Allow to toInt() to parse a string including "__" (#578)

Fix the issue where String#toInt() cannot parse a Int string
including sequence of "_" like "1_2__3___".
This commit is contained in:
Taichi Ishitani
2024-07-15 17:39:17 +09:00
committed by GitHub
parent cdf548cad0
commit b5e011dae1
3 changed files with 12 additions and 4 deletions

View File

@@ -768,7 +768,7 @@ public final class StringNodes {
@Specialization @Specialization
protected long eval(String self) { protected long eval(String self) {
try { try {
return Long.parseLong(self); return Long.parseLong(self.replaceAll("_", ""));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
throw exceptionBuilder() throw exceptionBuilder()
.evalError("cannotParseStringAs", "Int") .evalError("cannotParseStringAs", "Int")
@@ -783,7 +783,7 @@ public final class StringNodes {
@Specialization @Specialization
protected Object eval(String self) { protected Object eval(String self) {
try { try {
return Long.parseLong(self); return Long.parseLong(self.replaceAll("_", ""));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
return VmNull.withoutDefault(); return VmNull.withoutDefault();
} }

View File

@@ -225,6 +225,8 @@ examples {
["toInt()"] { ["toInt()"] {
"123".toInt() "123".toInt()
"-123".toInt() "-123".toInt()
"1_2__3___".toInt()
"-1_2__3___".toInt()
"0".toInt() "0".toInt()
"-0".toInt() "-0".toInt()
module.catch(() -> "1.2".toInt()) module.catch(() -> "1.2".toInt())
@@ -236,6 +238,8 @@ examples {
["toIntOrNull()"] { ["toIntOrNull()"] {
"123".toIntOrNull() "123".toIntOrNull()
"-123".toIntOrNull() "-123".toIntOrNull()
"1_2__3___".toInt()
"-1_2__3___".toInt()
"0".toIntOrNull() "0".toIntOrNull()
"-0".toIntOrNull() "-0".toIntOrNull()
"1.2".toIntOrNull() "1.2".toIntOrNull()
@@ -445,7 +449,7 @@ examples {
"".sha256 "".sha256
quickBrownFox.sha256 quickBrownFox.sha256
} }
["sha256Int"] { ["sha256Int"] {
"".sha256Int "".sha256Int
quickBrownFox.sha256Int quickBrownFox.sha256Int
@@ -460,7 +464,7 @@ examples {
"".base64 "".base64
quickBrownFox.base64 quickBrownFox.base64
} }
["base64Decoded"] { ["base64Decoded"] {
module.catch(() -> "~~~".base64Decoded) module.catch(() -> "~~~".base64Decoded)
} }

View File

@@ -181,6 +181,8 @@ examples {
List(97, 98, 99, 100, 101, 102, 103) List(97, 98, 99, 100, 101, 102, 103)
} }
["toInt()"] { ["toInt()"] {
123
-123
123 123
-123 -123
0 0
@@ -191,6 +193,8 @@ examples {
"Cannot parse string as `Int`. String: \"abc\"" "Cannot parse string as `Int`. String: \"abc\""
} }
["toIntOrNull()"] { ["toIntOrNull()"] {
123
-123
123 123
-123 -123
0 0