-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParseNumber.java
More file actions
49 lines (46 loc) · 1.3 KB
/
Copy pathParseNumber.java
File metadata and controls
49 lines (46 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package scottf;
public class ParseNumber {
public static int parseInt(String val) {
long l = parseLong(val);
if (l > (long)Integer.MAX_VALUE || l < (long)Integer.MIN_VALUE) {
throw new NumberFormatException(
"Input string outside results in a number outside of the range for an int: \"" + val + "\"");
}
return (int)l;
}
public static long parseLong(String val) {
String vl = val
.trim()
.toLowerCase()
.replaceAll("_", "")
.replaceAll(",", "")
.replaceAll("\\.", "");
long factor = 1;
int fl = 1;
if (vl.endsWith("k")) {
factor = 1000;
}
else if (vl.endsWith("ki")) {
factor = 1024;
fl = 2;
}
else if (vl.endsWith("m")) {
factor = 1_000_000;
}
else if (vl.endsWith("mi")) {
factor = 1024 * 1024;
fl = 2;
}
else if (vl.endsWith("g")) {
factor = 1_000_000_000;
}
else if (vl.endsWith("gi")) {
factor = 1024 * 1024 * 1024;
fl = 2;
}
if (factor > 1) {
vl = vl.substring(0, vl.length() - fl);
}
return Long.parseLong(vl) * factor;
}
}