|
5 | 5 |
|
6 | 6 | package org.opensearch.sql.expression.function.udf; |
7 | 7 |
|
| 8 | +import java.math.BigInteger; |
8 | 9 | import java.util.List; |
9 | 10 | import org.apache.calcite.adapter.enumerable.NotNullImplementor; |
10 | 11 | import org.apache.calcite.adapter.enumerable.NullPolicy; |
@@ -69,50 +70,23 @@ public static Number toNumber(String numStr) { |
69 | 70 | @Strict |
70 | 71 | public static Number toNumber(String numStr, int base) { |
71 | 72 | if (base < 2 || base > 36) { |
72 | | - throw new IllegalArgumentException("Base must be between 2 and 36"); |
| 73 | + throw new IllegalArgumentException("Base has to be between 2 and 36."); |
73 | 74 | } |
74 | | - |
75 | | - if (numStr.contains(".")) { |
76 | | - |
77 | | - boolean isNegative = numStr.startsWith("-"); |
78 | | - if (isNegative) { |
79 | | - numStr = numStr.substring(1); |
80 | | - } |
81 | | - |
82 | | - // Split integer and fractional parts |
83 | | - String[] parts = numStr.split("\\."); |
84 | | - String intPart = parts[0]; |
85 | | - String fracPart = parts.length > 1 ? parts[1] : ""; |
86 | | - |
87 | | - // Convert integer part |
88 | | - double intValue = 0; |
89 | | - for (char c : intPart.toCharArray()) { |
90 | | - int digit = Character.digit(c, base); |
91 | | - if (digit < 0) throw new IllegalArgumentException("Invalid digit: " + c); |
92 | | - intValue = intValue * base + digit; |
93 | | - } |
94 | | - |
95 | | - // Convert fractional part |
96 | | - double fracValue = 0; |
| 75 | + Number result = null; |
| 76 | + try { |
97 | 77 | if (base == 10) { |
98 | | - double divisor = base; |
99 | | - for (char c : fracPart.toCharArray()) { |
100 | | - int digit = Character.digit(c, base); |
101 | | - if (digit < 0) throw new IllegalArgumentException("Invalid digit: " + c); |
102 | | - fracValue += (double) digit / divisor; |
103 | | - divisor *= base; |
| 78 | + if (numStr.contains(".")) { |
| 79 | + result = Double.parseDouble(numStr); |
| 80 | + } else { |
| 81 | + result = Long.parseLong(numStr); |
104 | 82 | } |
105 | | - } |
106 | | - |
107 | | - double result = intValue + fracValue; |
108 | | - result = isNegative ? -result : result; |
109 | | - if (base == 10) { |
110 | | - return result; |
111 | 83 | } else { |
112 | | - return (long) result; |
| 84 | + BigInteger bigInteger = new BigInteger(numStr, base); |
| 85 | + result = bigInteger.longValue(); |
113 | 86 | } |
114 | | - } else { |
115 | | - return Long.parseLong(numStr, base); |
| 87 | + } catch (Exception e) { |
| 88 | + |
116 | 89 | } |
| 90 | + return result; |
117 | 91 | } |
118 | 92 | } |
0 commit comments