90 lines
3 KiB
Text
90 lines
3 KiB
Text
import ballerina/io;
|
|
|
|
function commatize(string s, int begin = 0, int step = 3, string sep = ",") {
|
|
var invert = function(string n) returns string {
|
|
string t = "";
|
|
foreach int i in int:range(n.length() - 1, -1, -1) { t += n[i]; }
|
|
return t;
|
|
};
|
|
|
|
var addSeps = function(string nn, boolean dp) returns string {
|
|
string n = nn;
|
|
string lz = "";
|
|
if !dp && n.startsWith("0") && n != "0" {
|
|
string:RegExp pattern = re `^0+`;
|
|
string k = pattern.replace(n, "");
|
|
if k == "" { k = "0"; }
|
|
foreach int i in 1 ... n.length() - k.length() { lz += "0"; }
|
|
n = k;
|
|
}
|
|
if dp { n = invert(n); } // invert if after decimal point
|
|
int i = n.length() - step;
|
|
while i >= 1 {
|
|
n = n.substring(0, i) + sep + n.substring(i);
|
|
i -= step;
|
|
}
|
|
if dp { n = invert(n); } // invert back
|
|
return lz + n;
|
|
};
|
|
|
|
var isExponent = function(string:Char c) returns boolean {
|
|
return "eEdDpP^∙x↑*⁰¹²³⁴⁵⁶⁷⁸⁹".includes(c);
|
|
};
|
|
|
|
string t = s;
|
|
string acc = (begin == 0) ? "" : t.substring(0, begin);
|
|
string n = "";
|
|
boolean dp = false;
|
|
foreach int j in begin ..< t.length() {
|
|
string:Char c = t[j];
|
|
if c >= "0" && c <= "9" {
|
|
n += t[j];
|
|
if j == t.length() - 1 {
|
|
if acc != "" && isExponent(acc[acc.length() - 1]) {
|
|
acc = s;
|
|
} else {
|
|
acc += addSeps(n, dp);
|
|
}
|
|
}
|
|
} else if n != "" {
|
|
if acc != "" && isExponent(acc[acc.length() - 1]) {
|
|
acc = s;
|
|
break;
|
|
} else if t[j] != "." {
|
|
acc += addSeps(n, dp) + t.substring(j);
|
|
break;
|
|
} else {
|
|
acc += addSeps(n, dp) + t[j];
|
|
dp = true;
|
|
n = "";
|
|
}
|
|
} else {
|
|
acc += t[j];
|
|
}
|
|
}
|
|
io:println(s);
|
|
io:println(acc);
|
|
io:println();
|
|
}
|
|
|
|
public function main() {
|
|
commatize("123456789.123456789", 0, 2, "*");
|
|
commatize(".123456789", 0, 3, "-");
|
|
commatize("57256.1D-4", 0, 4, "__");
|
|
commatize("pi=3.14159265358979323846264338327950288419716939937510582097494459231", 0, 5, " ");
|
|
commatize("The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 0, 3, ".");
|
|
|
|
string[] defaults = [
|
|
"\"-in Aus$+1411.8millions\"",
|
|
"===US$0017440 millions=== (in 2000 dollars)",
|
|
"123.e8000 is pretty big.",
|
|
"The land area of the earth is 57268900(29% of the surface) square miles.",
|
|
"Ain't no numbers in this here words, nohow, no way, Jose.",
|
|
"James was never known as 0000000007",
|
|
"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.",
|
|
" $-140000±100 millions.",
|
|
"6/9/1946 was a good year for some."
|
|
];
|
|
|
|
foreach string d in defaults { commatize(d); }
|
|
}
|