Commatizing numbers: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(→‎{{header|D}}: inserted missing braces)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(50 intermediate revisions by 22 users not shown)
Line 1:
{{task|Arithmetic operations}}
<!-- commatiz or commatize !-->
 
''Commatizing'' &nbsp; numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string.
 
 
Line 40 ⟶ 41:
::::::* &nbsp; 7500<b>∙</b>10**35
::::::* &nbsp; 8500x10**35
::::::* &nbsp; 9500↑35
::::::* &nbsp; +55000↑3
::::::* &nbsp; 1000**100
Line 78 ⟶ 80:
 
;Also see:
* The Wiki entry: &nbsp; [http://en.wikipedia.org/wiki/Eddington_number (sir) Arthur Eddington's number of protons in the universe]. <br><br>
 
=={{header|11l}}==
{{trans|Nim}}
 
<syntaxhighlight lang="11l">F commatize(s, period = 3, sep = ‘,’)
V m = re:‘(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)’.search(s)
I !m
R s
 
V match = m.group()
V splits = match.split(‘.’)
 
V ip = splits[0]
I ip.len > period
V inserted = 0
L(i) ((ip.len - 1) % period + 1 .< ip.len).step(period)
ip = ip[0 .< i + inserted]‘’sep‘’ip[i + inserted ..]
inserted += sep.len
 
I splits.len > 1
V dp = splits[1]
I dp.len > period
L(i) ((dp.len - 1) I/ period * period .< period - 1).step(-period)
dp = dp[0 .< i]‘’sep‘’dp[i..]
ip ‘’= ‘.’dp
 
R s[0 .< m.start()]‘’ip‘’s[m.end()..]
 
V tests = [‘123456789.123456789’,
‘.123456789’,
‘57256.1D-4’,
‘pi=3.14159265358979323846264338327950288419716939937510582097494459231’,
‘The author has two Z$100000000000000 Zimbabwe notes (100 trillion).’,
‘-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.’]
 
print(commatize(tests[0], period' 2, sep' ‘*’))
print(commatize(tests[1], period' 3, sep' ‘-’))
print(commatize(tests[2], period' 4, sep' ‘__’))
print(commatize(tests[3], period' 5, sep' ‘ ’))
print(commatize(tests[4], sep' ‘.’))
 
L(test) tests[5..]
print(commatize(test))</syntaxhighlight>
 
{{out}}
<pre>
1*23*45*67*89.12*34*56*78*9
.123-456-789
5__7256.1D-4
pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).
-in Aus$+1,411.8millions
===US$0017,440 millions=== (in 2000 dollars)
123.e8000 is pretty big.
The land area of the earth is 57,268,900(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 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.
$-140,000±100 millions.
6/9/1946 was a good year for some.
</pre>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># returns text commatized according to the rules of the task and the #
# period, location and separator paramters #
PROC commatize = ( STRING text, INT location, INT period, STRING separator )STRING:
Line 167 ⟶ 240:
newline ) );
print( ( COMMATIZE " $-140000±100 millions.", newline ) );
print( ( COMMATIZE "6/9/1946 was a good year for some.", newline ) )</langsyntaxhighlight>
{{out}}
<pre>
Line 183 ⟶ 256:
</pre>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
static string[] inputs = {
"pi=3.14159265358979323846264338327950288419716939937510582097494459231",
Line 233 ⟶ 306:
}
}
</syntaxhighlight>
</lang>
 
=={{header|D}}==
Better to have more tests than more features.
The function commatize is a solution. The function commatizeSpec adds extra features, to detect all formats in the examples in one function call.
<langsyntaxhighlight lang="d">import std.stdio, std.regex, std.range;
 
// A decimal integer field begins with zero then no digit, or a non-zero digit.
auto decIntField = ctRegex!("0(?![0-9])|[1-9][0-9]*");
// A decimal fractional field is joined by only a point, and is only digits.
auto decFracField = ctRegex!("(?<=^\\.)[0-9]+");
 
auto commatize(in char[] txt, in uint start=0, in uint step=3,
in string ins=",") @safe
in {
assert(step > 0);
Line 251 ⟶ 319:
if (start > txt.length || step > txt.length)
return txt;
auto matchInt = matchFirst(txt[start .. $], decIntField);
if (!matchInt)
return txt;
return txt[0 .. start] ~ matchInt.pre ~
matchInt.hit
.replace!(m => m.hit.retro.chunks(step).join(ins).retro)(decIntField) ~
matchInt.post
.replace!(m => m.hit.chunks(step).join(ins))(decFracField);
}
 
// First number may begin with digit or decimal point. Exponents ignored.
// The following function can be called with the same arguments as commatize,
enum decFloField = ctRegex!("[0-9]*\\.[0-9]+|[0-9]+");
// or with more optional arguments as well, for an overcomplicated file task,
// such as writing only one call to meet this task's minimal requirements.
 
auto matchDec = matchFirst(txt[start .. $], decFloField);
auto commatizeSpec(bool extraSpecial=false, // extra special treatments:
if (!matchDec)
// 36 digits allows decillions (US size). Integer parts long enough
// for undecillions will use the alternate separator at least.
// The task's Wikipedia reference uses spaces in Eddington number.
uint sepAltDigitLen=36, string sepAlt=" ",
// 33 digits allows decillionths. Decimal fractions long enough
// for undecillionths will use the alternate separator and step.
uint stepAltDigitLen=33, uint stepAlt=5,)
(in char[] txt, in uint start=0, in uint step=3,
in string sep=",", string[string] sepByPrefix=null) {
if (start > txt.length)
return txt;
uint stepAdj = step;
string sepAdj = sep;
if (sepByPrefix !is null) {
auto preAnyDigit = matchFirst(txt[start .. $], ctRegex!"[0-9]").pre;
// A longer prefix match will override a shorter match length.
ulong matchLength = 0;
foreach (pair; sepByPrefix.byPair) {
auto prefix = pair[0];
if (preAnyDigit.length >= prefix.length &&
prefix.length > matchLength &&
prefix == preAnyDigit[$ - prefix.length .. $]) {
sepAdj = pair[1];
matchLength = prefix.length;
}
}
}
if (extraSpecial) {
auto wholeDig = matchFirst(txt[start .. $], decIntField);
auto fracDig = matchFirst(wholeDig.post, decFracField);
if (wholeDig && fracDig && fracDig.hit.length > stepAltDigitLen) {
sepAdj = sepAlt;
stepAdj = stepAlt;
} else if (wholeDig && wholeDig.hit.length > sepAltDigitLen) {
sepAdj = sepAlt;
}
}
return sep == "" ? txt : commatize(txt, start, stepAdj, sepAdj);
}
 
// Within a decimal float field:
void main() {
// A decimal integer field to commatize is positive and not after a point.
foreach (const line; "commatizing_numbers_data.txt".File.byLine)
enum decIntField = ctRegex!("(?<=\\.)|[1-9][0-9]*");
line.commatizeSpec!true(0, 3, ",", ["Z$":"."]).writeln;
// A decimal fractional field is preceded by a point, and is only digits.
enum decFracField = ctRegex!("(?<=\\.)[0-9]+");
 
return txt[0 .. start] ~ matchDec.pre ~ matchDec.hit
.replace!(m => m.hit.retro.chunks(step).join(ins).retro)(decIntField)
.replace!(m => m.hit.chunks(step).join(ins))(decFracField)
~ matchDec.post;
}
 
unittest {
// An attempted solution may have one or more of the following errors:
// ignoring a number that has only zero before its decimal point
assert("0.0123456".commatize == "0.012,345,6");
// commatizing numbers other than the first
assert("1000 2.3000".commatize == "1,000 2.3000");
// only commatizing in one direction from the decimal point
assert("0001123.456789".commatize == "0001,123.456,789");
// detecting prefixes such as "Z$" requires detecting other prefixes
// tests of the special prefix switch:
assert("Z NZ$01000300000".commatizeSpec(0, 3, ",", ["Z$":" "])commatize == "Z NZ$01 300,000");
// detecting a decimal field that isn't attached to the first number
assert("1. NZ$300000".commatizeSpec(1, 3, " ", ["Z$":".", "NZ$":","]) ==
assert(" 2600 and .0125".commatize == "1. NZ$3002,000600 and .0125");
// tests of ignoring the extrastart value, or specialconfusing switchbase on0 exceeding(used somehere) numberwith ofbase digits:1
assert("1000001 77000".commatizeSpec!(true, 6, " ", 10)commatize(1) == "1001 77,000");
// ignoring a number that begins with a point, or treating it as integer
assert("1000000".commatizeSpec!(true, 6, " ", 10)() == "1 000 000");
assert("0 .0000010104004".commatizeSpec!(true, 10, " ", 6)()commatize == "0 .000010,001400,4");
}
assert("0.0000001".commatizeSpec!(true, 10, " ", 6)() == "0.00000 01");
 
assert("x".commatizeSpec!true(2) == "x");
void main() {
}</lang>
"pi=3.14159265358979323846264338327950288419716939937510582097494459231"
.commatize(0, 5, " ").writeln;
"The author has two Z$100000000000000 Zimbabwe notes (100 trillion)."
.commatize(0, 3, ".").writeln;
foreach (const line; "commatizing_numbers_using_defaults.txt".File.byLine)
line.commatize.writeln;
}</syntaxhighlight>
{{out}}
<pre>pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
Line 335 ⟶ 374:
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 15 ,747 ,724 ,136 ,275 ,002 ,577 ,605 ,653 ,961 ,181 ,555 ,468 ,044 ,717 ,914 ,527 ,116 ,709 ,366 ,231 ,425 ,076 ,185 ,631 ,031 ,296 protons in the universe.
$-140,000±100 millions.
6/9/1946 was a good year for some.</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.RegularExpressions}}
{{libheader| system.StrUtils}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
program Commatizing_numbers;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
System.RegularExpressions,
system.StrUtils;
 
const
PATTERN = '(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)';
TESTS: array[0..13] of string = ('123456789.123456789', '.123456789',
'57256.1D-4', 'pi=3.14159265358979323846264338327950288419716939937510582097494459231',
'The author has two Z$100000000000000 Zimbabwe notes (100 trillion).',
'-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.');
 
var
regex: TRegEx;
 
function Commatize(s: string; startIndex, period: integer; sep: string): string;
var
m: TMatch;
s1, ip, pi, dp: string;
splits: TArray<string>;
i: integer;
begin
regex := TRegEx.Create(PATTERN);
 
if (startIndex < 0) or (startIndex >= s.Length) or (period < 1) or (sep.IsEmpty) then
exit(s);
m := regex.Match(s.Substring(startIndex, s.Length));
if not m.Success then
exit(s);
 
s1 := m.Groups[0].Value;
splits := s1.Split(['.']);
 
ip := splits[0];
 
if ip.Length > period then
begin
pi := ReverseString(ip);
i := ((ip.Length - 1) div period) * period;
 
while i >= period do
begin
pi := pi.Substring(0, i) + sep + pi.Substring(i);
i := i - period;
end;
ip := ReverseString(pi);
end;
 
if s1.Contains('.') then
begin
dp := splits[1];
if dp.Length > period then
begin
i := ((dp.Length - 1) div period) * period;
while i >= period do
begin
dp := dp.Substring(0, i) + sep + dp.Substring(i);
i := i - period;
end;
end;
ip := ip + '.' + dp;
end;
Result := s.Substring(0, startIndex) + s.Substring(startIndex).Replace(s1, ip, []);
end;
 
var
i: integer;
 
begin
Writeln(commatize(TESTS[0], 0, 2, '*'));
Writeln(commatize(TESTS[1], 0, 3, '-'));
Writeln(commatize(TESTS[2], 0, 4, '__'));
Writeln(commatize(TESTS[3], 0, 5, ' '));
Writeln(commatize(TESTS[4], 0, 3, '.'));
for i := 5 to High(TESTS) do
Writeln(commatize(TESTS[i], 0, 3, ','));
readln;
end.</syntaxhighlight>
 
=={{header|Factor}}==
{{works with|Factor|0.99 2020-01-23}}
<syntaxhighlight lang="factor">USING: accessors grouping io kernel math regexp sequences
splitting strings unicode ;
 
: numeric ( str -- new-str )
R/ [1-9][0-9]*/ first-match >string ;
 
: commas ( numeric-str period separator -- str )
[ reverse ] [ group ] [ reverse join reverse ] tri* ;
 
: (commatize) ( text from period separator -- str )
[ cut dup numeric dup ] 2dip commas replace append ;
 
: commatize* ( text from period separator -- str )
reach [ digit? ] any? [ (commatize) ] [ 3drop ] if ;
 
: commatize ( text -- str ) 0 3 "," commatize* ;
 
"pi=3.14159265358979323846264338327950288419716939937510582097494459231"
5 5 " " commatize* print
"The author has two Z$100000000000000 Zimbabwe notes (100 trillion)."
0 3 "." commatize* print
{
"\"-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."
} [ commatize print ] each</syntaxhighlight>
{{out}}
<pre>
pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).
"-in Aus$+1,411.8millions"
===US$0017,440 millions=== (in 2000 dollars)
123.e8000 is pretty big.
The land area of the earth is 57,268,900(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 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.
$-140,000±100 millions.
6/9/1946 was a good year for some.
</pre>
 
 
=={{header|FreeBASIC}}==
{{trans|VBA}}
{{trans|Phix}}
<syntaxhighlight lang="freebasic">Sub commatize(s As String, sep As String = ",", start As Byte = 1, paso As Byte = 3)
Dim As Integer l = Len(s)
For i As Integer = start To l
If Asc(Mid(s, i, 1)) >= Asc("1") And Asc(Mid(s, i, 1)) <= Asc("9") Then
For j As Integer =i+1 To l+1
If j>l Then
For k As Integer = j-1-paso To i Step -paso
s = Mid(s, 1, k) + sep + Mid(s, k+1, l-k+1)
l = Len(s)
Next k
Exit For
Else
If (Asc(Mid(s, j, 1)) < Asc("0") Or Asc(Mid(s, j, 1)) > Asc("9")) Then
For k As Integer = j-1-paso To i Step -paso
s = Mid(s, 1, k) + sep + Mid(s, k+1, l-k+1)
l = Len(s)
Next k
Exit For
End If
End If
Next j
Exit For
End If
Next i
Print s
End Sub
 
commatize("pi=3.14159265358979323846264338327950288419716939937510582097494459231"," ",6,5)
commatize("The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",".")
commatize("\'-in Aus$+1411.8millions\'",",")
commatize("===US$0017440 millions=== (in 2000 dollars)")
commatize("123.e8000 is pretty big.")
commatize("The land area of the earth is 57268900(29% of the surface) square miles.")
commatize("Ain't no numbers in this here words, nohow, no way, Jose.")
commatize("James was never known as 0000000007")
commatize("Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.")
commatize(" $-140000±100 millions.")
commatize("6/9/1946 was a good year for some.")
 
Sleep</syntaxhighlight>
{{out}}
<pre>
Similar a las entradas de VBA o Phix.
</pre>
 
 
 
=={{header|FutureBasic}}==
Note: FB throws an error when function parameters are missing, hence the need for placeholders.
<syntaxhighlight lang="futurebasic">
local fn commatize( s as Str255, sep as Str255, start as long, stp as long )
if sep[0] == 0 then sep = ","
if start == 0 then start = 1
if stp == 0 then stp = 3
long i, j, k, l = len$(s)
for i = start to l
if ( asc( mid$( s, i, 1 ) ) >= asc("1") and asc( mid$( s, i, 1) ) <= asc("9") )
for j = i + 1 to l + 1
if ( j > l )
for k = j - 1 - stp to i step -stp
s = mid$( s, 1, k ) + sep + mid$( s, k + 1, l - k + 1 )
l = len$(s)
next k
exit for
else
if ( asc( mid$( s, j, 1 ) ) < asc("0") or asc( mid$( s, j, 1 ) ) > asc("9") )
for k = j - 1 - stp to i step -stp
s = mid$( s, 1, k ) + sep + mid$( s, k + 1, l - k + 1 )
l = len$(s)
next k
exit for
end if
end if
next j
exit for
end if
next i
print s
end fn
 
window 1
 
fn commatize("pi=3.14159265358979323846264338327950288419716939937510582097494459231" , " " , 6, 5 )
fn commatize("The author has two Z$100000000000000 Zimbabwe notes (100 trillion)." , "." , 0, 0 )
fn commatize("\'-in Aus$+1411.8millions\'" , "," , 0, 0 )
fn commatize("===US$0017440 millions=== (in 2000 dollars)" , "" , 0, 0 )
fn commatize("123.e8000 is pretty big." , "" , 0, 0 )
fn commatize("The land area of the earth is 57268900(29% of the surface) square miles." , "" , 0, 0 )
fn commatize("Ain't no numbers in this here words, nohow, no way, Jose." , "" , 0, 0 )
fn commatize("James was never known as 0000000007" , "" , 0, 0 )
fn commatize("Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.", ",", 0, 0 )
fn commatize(" $-140000±100 millions." , "" , 0, 0 )
fn commatize("6/9/1946 was a good year for some." , "" , 0, 0 )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).
"-in Aus$+1,411.8millions"
===US$0017,440 millions=== (in 2000 dollars)
123.e8000 is pretty big.
The land area of the earth is 57,268,900(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 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.
$-140,000±100 millions.
6/9/1946 was a good year for some.
</pre>
 
 
 
=={{header|Go}}==
{{trans|Kotlin}}
<syntaxhighlight lang="go">package main
 
import (
"fmt"
"regexp"
"strings"
)
 
var reg = regexp.MustCompile(`(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)`)
 
func reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
 
func commatize(s string, startIndex, period int, sep string) string {
if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == "" {
return s
}
m := reg.FindString(s[startIndex:]) // this can only contain ASCII characters
if m == "" {
return s
}
splits := strings.Split(m, ".")
ip := splits[0]
if len(ip) > period {
pi := reverse(ip)
for i := (len(ip) - 1) / period * period; i >= period; i -= period {
pi = pi[:i] + sep + pi[i:]
}
ip = reverse(pi)
}
if strings.Contains(m, ".") {
dp := splits[1]
if len(dp) > period {
for i := (len(dp) - 1) / period * period; i >= period; i -= period {
dp = dp[:i] + sep + dp[i:]
}
}
ip += "." + dp
}
return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1)
}
 
func main() {
tests := [...]string{
"123456789.123456789",
".123456789",
"57256.1D-4",
"pi=3.14159265358979323846264338327950288419716939937510582097494459231",
"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",
"-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.",
}
fmt.Println(commatize(tests[0], 0, 2, "*"))
fmt.Println(commatize(tests[1], 0, 3, "-"))
fmt.Println(commatize(tests[2], 0, 4, "__"))
fmt.Println(commatize(tests[3], 0, 5, " "))
fmt.Println(commatize(tests[4], 0, 3, "."))
for _, test := range tests[5:] {
fmt.Println(commatize(test, 0, 3, ","))
}
}</syntaxhighlight>
 
{{out}}
<pre>
1*23*45*67*89.12*34*56*78*9
.123-456-789
5__7256.1D-4
pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).
-in Aus$+1,411.8millions
===US$0017,440 millions=== (in 2000 dollars)
123.e8000 is pretty big.
The land area of the earth is 57,268,900(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 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.
$-140,000±100 millions.
6/9/1946 was a good year for some.
</pre>
 
=={{header|Haskell}}==
 
{{Works with|GHC|7.8.3}}
{{Works with|GHC|8.6.5}}
 
<syntaxhighlight lang="haskell">#!/usr/bin/env runhaskell
 
import Control.Monad (forM_)
import Data.Char (isDigit)
import Data.List (intercalate)
import Data.Maybe (fromMaybe)
 
{-
I use the suffix "2" in identifiers in place of the more conventional
prime (single quote character), because Rosetta Code's syntax highlighter
still doesn't handle primes in identifiers correctly.
-}
 
isDigitOrPeriod :: Char -> Bool
isDigitOrPeriod '.' = True
isDigitOrPeriod c = isDigit c
 
chopUp :: Int -> String -> [String]
chopUp _ [] = []
chopUp by str
| by < 1 = [str] -- invalid argument, leave string unchanged
| otherwise = let (pfx, sfx) = splitAt by str
in pfx : chopUp by sfx
 
addSeps :: String -> Char -> Int -> (String -> String) -> String
addSeps str sep by rev =
let (leading, number) = span (== '0') str
number2 = rev $ intercalate [sep] $ chopUp by $ rev number
in leading ++ number2
 
processNumber :: String -> Char -> Int -> String
processNumber str sep by =
let (beforeDecimal, rest) = span isDigit str
(decimal, afterDecimal) = splitAt 1 rest
beforeDecimal2 = addSeps beforeDecimal sep by reverse
afterDecimal2 = addSeps afterDecimal sep by id
in beforeDecimal2 ++ decimal ++ afterDecimal2
 
commatize2 :: String -> Char -> Int -> String
commatize2 [] _ _ = []
commatize2 str sep by =
let (pfx, sfx) = break isDigitOrPeriod str
(number, sfx2) = span isDigitOrPeriod sfx
in pfx ++ processNumber number sep by ++ sfx2
 
commatize :: String -> Maybe Char -> Maybe Int -> String
commatize str sep by = commatize2 str (fromMaybe ',' sep) (fromMaybe 3 by)
 
input :: [(String, Maybe Char, Maybe Int)]
input =
[ ("pi=3.14159265358979323846264338327950288419716939937510582097494459231", Just ' ', Just 5)
, ("The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", Just '.', Nothing)
, ("\"-in Aus$+1411.8millions\"", Nothing, Nothing)
, ("===US$0017440 millions=== (in 2000 dollars)", Nothing, Nothing)
, ("123.e8000 is pretty big.", Nothing, Nothing)
, ("The land area of the earth is 57268900(29% of the surface) square miles.", Nothing, Nothing)
, ("Ain't no numbers in this here words, nohow, no way, Jose.", Nothing, Nothing)
, ("James was never known as 0000000007", Nothing, Nothing)
, ("Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.", Nothing, Nothing)
, (" $-140000±100 millions.", Nothing, Nothing)
, ("6/9/1946 was a good year for some.", Nothing, Nothing)
]
 
main :: IO ()
main =
forM_ input $ \(str, by, sep) -> do
putStrLn str
putStrLn $ commatize str by sep
putStrLn ""</syntaxhighlight>
{{out}}
<pre>
pi=3.14159265358979323846264338327950288419716939937510582097494459231
pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
 
The author has two Z$100000000000000 Zimbabwe notes (100 trillion).
The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).
 
"-in Aus$+1411.8millions"
"-in Aus$+1,411.8millions"
 
===US$0017440 millions=== (in 2000 dollars)
===US$0017,440 millions=== (in 2000 dollars)
 
123.e8000 is pretty big.
123.e8000 is pretty big.
 
The land area of the earth is 57268900(29% of the surface) square miles.
The land area of the earth is 57,268,900(29% of the surface) square miles.
 
Ain't no numbers in this here words, nohow, no way, Jose.
Ain't no numbers in this here words, nohow, no way, Jose.
 
James was never known as 0000000007
James was never known as 0000000007
 
Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.
Arthur Eddington wrote: I believe there are 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.
 
$-140000±100 millions.
$-140,000±100 millions.
 
6/9/1946 was a good year for some.
6/9/1946 was a good year for some.
 
</pre>
 
=={{header|J}}==
These rules are relatively baroque, which demands long names and minimally complex statements, thus:
 
<langsyntaxhighlight Jlang="j">require'regex'
commatize=:3 :0"1 L:1 0
(i.0) commatize y
Line 362 ⟶ 875:
fixed=. numb,;delim&,each (-period)<\ (#numb)}.number
prefix,(start{.text),fixed,(start+len)}.text
)</langsyntaxhighlight>
 
In use, this might look like:
 
<langsyntaxhighlight Jlang="j"> (5;5;' ') commatize 'pi=3.14159265358979323846264338327950288419716939937510582097494459231'
pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
'.' commatize 'The author has two Z$100000000000000 Zimbabwe notes (100 trillion).'
Line 387 ⟶ 900:
$-140,000±100 millions.
commatize '6/9/1946 was a good year for some.'
6/9/1946 was a good year for some.</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.io.File;
import java.util.*;
import java.util.regex.*;
Line 429 ⟶ 942:
System.out.println(m.appendTail(result));
}
}</langsyntaxhighlight>
 
<pre>pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
Line 443 ⟶ 956:
6/9/1946 was a good year for some.</pre>
 
=={{header|Perl 6jq}}==
'''Adapted from [[#Wren|Wren]]'''
<lang perl6>commatize 'pi=3.14159265358979323846264338327950288419716939937510582097494459231', :at(6), :ins(' '), :by(5);
{{works with|jq}}
commatize 'The author has two Z$100000000000000 Zimbabwe notes (100 trillion).', :ins<.>;
'''Also works with gojq, the Go implementation of jq.'''
commatize '-in Aus$+1411.8millions';
<syntaxhighlight lang="jq">
commatize '===US$0017440 millions=== (in 2000 dollars)';
def commatize($s; '123.e8000$start; is pretty big.'$step; $sep):
 
commatize 'The land area of the earth is 57268900(29% of the surface) square miles.';
def isExponent($c): "eEdDpP^∙x↑*⁰¹²³⁴⁵⁶⁷⁸⁹" | index($c);
commatize 'Ain\'t no numbers in this here words, nohow, no way, Jose.';
def rev: explode|reverse|implode;
commatize 'James was never known as 0000000007';
def addSeps($n; $dp):
commatize 'Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.';
{ $n, lz: "" }
commatize ' $-140000±100 millions.';
| if ($dp|not) and ($n|startswith("0")) and $n != "0"
commatize '6/9/1946 was a good year for some.';
then .k = ($n|sub("^0*";""))
| if (.k == "") then .k = "0" else . end
| .lz = "0" * (($n|length) - (.k|length))
| .n = .k
else .
end
| if $dp
then .n |= rev # reverse if after decimal point
else .
end
| .i = (.n|length) - $step
| until (.i < 1;
.n = .n[: .i] + $sep + .n[.i :]
| .i += - $step )
| if $dp
then .n |= rev # reverse again
else .
end
| .lz + .n;
 
{ acc: $s[:$start],
n: "",
dp: false }
| label $out
| foreach (range($start; $s|length), null) as $j (.;
if $j == null then .emit = true
else $s[$j:$j+1] as $x
| ($x | explode[0]) as $c
| if ($c >= 48 and $c <= 57)
then .n += $x
| if $j == (($s|length)-1)
then if (.acc != "" and isExponent(.acc[-1:]))
then .acc = $s
else .acc += addSeps(.n; .dp)
end
else .
end
elif .n != ""
then if (.acc != "" and isExponent(.acc[-1:]))
then .acc = $s
| .emit=true | ., break $out
elif $x != "."
then .acc += addSeps(.n; .dp) + $s[$j:]
| .emit=true | ., break $out
else .acc += addSeps(.n; .dp) + $x
| .dp = true
| .n = ""
end
else .acc += $x
end
end )
| select(.emit)
| $s, .acc, ""
;
 
# Input: the string to be commatized
def commatize:
commatize(.; 0; 3; ",");
 
def 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."
];
 
def exercise:
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; "."),
 
(defaults[] | commatize) ;
 
exercise
</syntaxhighlight>
{{output}}
Exactly as for [[#Wren|Wren]].
 
=={{header|Julia}}==
{{trans|Perl}}
<syntaxhighlight lang="julia">input = [
["pi=3.14159265358979323846264338327950288419716939937510582097494459231", " ", 5],
[raw"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "."],
[raw"-in Aus$+1411.8millions"],
[raw"===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."],
[raw" $-140000±100 millions."],
["6/9/1946 was a good year for some."]]
 
function commatize(tst)
grouping = (length(tst) == 3) ? tst[3] : 3
sep = (length(tst) > 1) ? tst[2] : ","
rmend(s) = replace(s, Regex("$sep\\Z") =>"")
greg = Regex(".{$grouping}")
cins(str) = reverse(rmend(replace(reverse(str), greg => s -> s * sep)))
mat = match(Regex("(?<![eE\\/])([1-9]\\d{$grouping,})"), tst[1])
if mat != nothing
return replace(tst[1], mat.match => cins)
end
return tst[1]
end
 
for tst in input
println(commatize(tst))
end
</syntaxhighlight> {{output}} <pre>
pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).
-in Aus$+1,411.8millions
===US$0017,440 millions=== (in 2000 dollars)
123.e8000 is pretty big.
The land area of the earth is 57,268,900(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 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.
$-140,000±100 millions.
6/9/1946 was a good year for some.
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.4-3
 
val r = Regex("""(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)""")
 
fun String.commatize(startIndex: Int = 0, period: Int = 3, sep: String = ","): String {
if ((startIndex !in 0 until this.length) || period < 1 || sep == "") return this
val m = r.find(this, startIndex)
if (m == null) return this
val splits = m.value.split('.')
var ip = splits[0]
if (ip.length > period) {
val sb = StringBuilder(ip.reversed())
for (i in (ip.length - 1) / period * period downTo period step period) {
sb.insert(i, sep)
}
ip = sb.toString().reversed()
}
if ('.' in m.value) {
var dp = splits[1]
if (dp.length > period) {
val sb2 = StringBuilder(dp)
for (i in (dp.length - 1) / period * period downTo period step period) {
sb2.insert(i, sep)
}
dp = sb2.toString()
}
ip += "." + dp
}
return this.take(startIndex) + this.drop(startIndex).replaceFirst(m.value, ip)
}
 
fun main(args: Array<String>) {
val tests = arrayOf(
"123456789.123456789",
".123456789",
"57256.1D-4",
"pi=3.14159265358979323846264338327950288419716939937510582097494459231",
"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",
"-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."
)
 
println(tests[0].commatize(period = 2, sep = "*"))
println(tests[1].commatize(period = 3, sep = "-"))
println(tests[2].commatize(period = 4, sep = "__"))
println(tests[3].commatize(period = 5, sep = " "))
println(tests[4].commatize(sep = "."))
for (test in tests.drop(5)) println(test.commatize())
}</syntaxhighlight>
 
sub commatize($s, :$at = 0, :$ins = ',', :$by = 3) {
say "Before: ", $s;
say " After: ", $s.subst:
:continue($at), :1st,
/ <[1..9]> <[0..9]>* /,
*.flip.comb(/<{ ".**1..$by" }>/).join($ins).flip;
}</lang>
{{out}}
<pre>
<pre>Before: pi=3.14159265358979323846264338327950288419716939937510582097494459231
1*23*45*67*89.12*34*56*78*9
After: pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
.123-456-789
Before: The author has two Z$100000000000000 Zimbabwe notes (100 trillion).
5__7256.1D-4
After: The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).
pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
Before: -in Aus$+1411.8millions
The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).
After: -in Aus$+1,411.8millions
-in Aus$+1,411.8millions
Before: ===US$0017440 millions=== (in 2000 dollars)
After: ===US$0017,440 millions=== (in 2000 dollars)
Before: 123.e8000 is pretty big.
The land area of the earth is 57,268,900(29% of the surface) square miles.
After: 123.e8000 is pretty big.
Ain't no numbers in this here words, nohow, no way, Jose.
Before: The land area of the earth is 57268900(29% of the surface) square miles.
James was never known as 0000000007
After: The land area of the earth is 57,268,900(29% of the surface) square miles.
Arthur Eddington wrote: I believe there are 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.
Before: Ain't no numbers in this here words, nohow, no way, Jose.
$-140,000±100 millions.
After: Ain't no numbers in this here words, nohow, no way, Jose.
6/9/1946 was a good year for some.
Before: James was never known as 0000000007
</pre>
After: James was never known as 0000000007
Before: Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.
After: Arthur Eddington wrote: I believe there are 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.
Before: $-140000±100 millions.
After: $-140,000±100 millions.
Before: 6/9/1946 was a good year for some.
After: 6/9/1946 was a good year for some.</pre>
 
=={{header|PhixNim}}==
{{trans|Kotlin}}
<lang Phix>procedure commatize(string s, string sep=",", integer start=1, integer step=3)
This is a translation of the Kotlin (and Go) algorithm with some modifications.
integer l = length(s)
for i=start to l do
if find(s[i],"123456789") then
for j=i+1 to l+1 do
if j>l or not find(s[j],"0123456789") then
for k=j-1-step to i by -step do
s[k+1..k] = sep
end for
exit
end if
end for
exit
end if
end for
printf(1,"%s\n",{s})
end procedure
 
<syntaxhighlight lang="nim">import re
commatize("pi=3.14159265358979323846264338327950288419716939937510582097494459231"," ",6,5)
import strutils
commatize("The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",".")
 
commatize("\"-in Aus$+1411.8millions\"")
let r = re"(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)"
commatize("===US$0017440 millions=== (in 2000 dollars)")
 
commatize("123.e8000 is pretty big.")
#---------------------------------------------------------------------------------------------------
commatize("The land area of the earth is 57268900(29% of the surface) square miles.")
 
commatize("Ain't no numbers in this here words, nohow, no way, Jose.")
proc commatize(str: string; startIndex = 0; period = 3; sep = ","): string =
commatize("James was never known as 0000000007")
 
commatize("Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.")
result = str
commatize(" $-140000±100 millions.")
var dp, ip = ""
commatize("6/9/1946 was a good year for some.")</lang>
 
if startIndex notin 0..str.high : return
 
# Extract first number (if any).
let (lowBound, highBound) = str.findBounds(r, startIndex)
if lowBound < 0: return
let match = str[lowBound..highBound]
let splits = match.split('.')
 
# Process integer part.
ip = splits[0]
if ip.len > period:
var inserted = 0
for i in countup(ip.high mod period + 1, ip.high, period):
ip.insert(sep, i + inserted)
inserted += sep.len
 
# Process decimal part.
if '.' in match:
dp = splits[1]
if dp.len > period:
for i in countdown(dp.high div period * period, period, period):
dp.insert(sep, i)
ip &= '.' & dp
 
# Replace the number by its "commatized" version.
result[lowBound..highBound] = ip
 
 
#———————————————————————————————————————————————————————————————————————————————————————————————————
 
const Tests = [
"123456789.123456789",
".123456789",
"57256.1D-4",
"pi=3.14159265358979323846264338327950288419716939937510582097494459231",
"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",
"-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."]
 
 
echo Tests[0].commatize(period = 2, sep = "*")
echo Tests[1].commatize(period = 3, sep = "-")
echo Tests[2].commatize(period = 4, sep = "__")
echo Tests[3].commatize(period = 5, sep = " ")
echo Tests[4].commatize(sep = ".")
 
for n in 5..Tests.high:
echo Tests[n].commatize()</syntaxhighlight>
 
{{out}}
<pre>1*23*45*67*89.12*34*56*78*9
.123-456-789
5__7256.1D-4
pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).
-in Aus$+1,411.8millions
===US$0017,440 millions=== (in 2000 dollars)
123.e8000 is pretty big.
The land area of the earth is 57,268,900(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 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.
$-140,000±100 millions.
6/9/1946 was a good year for some.</pre>
 
=={{header|Perl}}==
Displaying before/after only when changes applied.
<syntaxhighlight lang="perl">@input = (
['pi=3.14159265358979323846264338327950288419716939937510582097494459231', ' ', 5],
['The author has two Z$100000000000000 Zimbabwe notes (100 trillion).', '.'],
['-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.'],
['5/9/1946 was a good year for some.']
);
 
for $i (@input) {
$old = @$i[0];
$new = commatize(@$i);
printf("%s\n%s\n\n", $old, $new) if $old ne $new;
}
 
sub commatize {
my($str,$sep,$by) = @_;
$sep = ',' unless $sep;
$by = 3 unless $by;
 
$str =~ s/ # matching rules:
(?<![eE\/]) # not following these characters
([1-9]\d{$by,}) # leading non-zero digit, minimum number of digits required
/c_ins($1,$by,$sep)/ex; # substitute matched text with subroutine output
return $str;
}
 
sub c_ins {
my($s,$by,$sep) = @_;
($c = reverse $s) =~ s/(.{$by})/$1$sep/g;
$c =~ s/$sep$//;
return reverse $c;
}</syntaxhighlight>
{{out}}
<pre>pi=3.14159265358979323846264338327950288419716939937510582097494459231
pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
 
The author has two Z$100000000000000 Zimbabwe notes (100 trillion).
The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).
 
-in Aus$+1411.8millions
-in Aus$+1,411.8millions
 
===US$0017440 millions=== (in 2000 dollars)
===US$0017,440 millions=== (in 2000 dollars)
 
The land area of the earth is 57268900(29% of the surface) square miles.
The land area of the earth is 57,268,900(29% of the surface) square miles.
 
Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.
Arthur Eddington wrote: I believe there are 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.
 
$-140000±100 millions.
$-140,000±100 millions.</pre>
 
=={{header|Phix}}==
Note that printf() has comma handling built in, for example sprintf("%,d",1234) yields "1,234".<br>
You can find out how that is done by searching for showcommas in builtins\VM\pprntfN.e or (actually JavaScript) in pwa\p2js.js
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">commatize</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">sep</span><span style="color: #0000FF;">=</span><span style="color: #008000;">","</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">start</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">step</span><span style="color: #0000FF;">=</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">start</span> <span style="color: #008080;">to</span> <span style="color: #000000;">l</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #008000;">"123456789"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">l</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">></span><span style="color: #000000;">l</span> <span style="color: #008080;">or</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span><span style="color: #008000;">"0123456789"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">j</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">-</span><span style="color: #000000;">step</span> <span style="color: #008080;">to</span> <span style="color: #000000;">i</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">step</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sep</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">commatize</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"pi=3.14159265358979323846264338327950288419716939937510582097494459231"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">commatize</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"The author has two Z$100000000000000 Zimbabwe notes (100 trillion)."</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"."</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">commatize</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"\"-in Aus$+1411.8millions\""</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">commatize</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"===US$0017440 millions=== (in 2000 dollars)"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">commatize</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"123.e8000 is pretty big."</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">commatize</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"The land area of the earth is 57268900(29% of the surface) square miles."</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">commatize</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Ain't no numbers in this here words, nohow, no way, Jose."</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">commatize</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"James was never known as 0000000007"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">commatize</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe."</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">commatize</span><span style="color: #0000FF;">(</span><span style="color: #008000;">" $-140000±100 millions."</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">commatize</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"6/9/1946 was a good year for some."</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 531 ⟶ 1,377:
6/9/1946 was a good year for some.
</pre>
 
=={{header|Python}}==
<syntaxhighlight lang="python">
import re as RegEx
 
 
def Commatize( _string, _startPos=0, _periodLen=3, _separator="," ):
outString = ""
strPos = 0
matches = RegEx.findall( "[0-9]*", _string )
 
for match in matches[:-1]:
if not match:
outString += _string[ strPos ]
strPos += 1
else:
if len(match) > _periodLen:
leadIn = match[:_startPos]
periods = [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ]
outString += leadIn + _separator.join( periods )
else:
outString += match
 
strPos += len( match )
 
return outString
 
 
 
print ( Commatize( "pi=3.14159265358979323846264338327950288419716939937510582097494459231", 0, 5, " " ) )
print ( Commatize( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 0, 3, "." ))
print ( Commatize( "\"-in Aus$+1411.8millions\"" ))
print ( Commatize( "===US$0017440 millions=== (in 2000 dollars)" ))
print ( Commatize( "123.e8000 is pretty big." ))
print ( Commatize( "The land area of the earth is 57268900(29% of the surface) square miles." ))
print ( Commatize( "Ain't no numbers in this here words, nohow, no way, Jose." ))
print ( Commatize( "James was never known as 0000000007" ))
print ( Commatize( "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." ))
print ( Commatize( "␢␢␢$-140000±100 millions." ))
print ( Commatize( "6/9/1946 was a good year for some." ))
</syntaxhighlight>
 
=={{header|Racket}}==
Line 541 ⟶ 1,428:
All tests pass (so it's as good as Perl, I guess).
 
<langsyntaxhighlight lang="racket">#lang racket
(require (only-in srfi/13 [string-reverse gnirts]))
 
Line 615 ⟶ 1,502:
(commatize "6/9/1946 was a good year for some.")
=>"6/9/1946 was a good year for some."))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>for ('pi=3.14159265358979323846264338327950288419716939937510582097494459231', {:6at, :5by, :ins(' ')}),
('The author has two Z$100000000000000 Zimbabwe notes (100 trillion).', {:ins<.>}),
'-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.'
{
say "Before: ", .[0];
say " After: ", .[1] ?? .[0].&commatize( |.[1] ) !! .&commatize;
}
sub commatize($s, :$at = 0, :$ins = ',', :$by = 3) {
$s.subst: :continue($at), :1st, / <[1..9]> <[0..9]>* /,
*.flip.comb(/<{ ".**1..$by" }>/).join($ins).flip;
}</syntaxhighlight>
{{out}}
<pre>Before: pi=3.14159265358979323846264338327950288419716939937510582097494459231
After: pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
Before: The author has two Z$100000000000000 Zimbabwe notes (100 trillion).
After: The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).
Before: -in Aus$+1411.8millions
After: -in Aus$+1,411.8millions
Before: ===US$0017440 millions=== (in 2000 dollars)
After: ===US$0017,440 millions=== (in 2000 dollars)
Before: 123.e8000 is pretty big.
After: 123.e8000 is pretty big.
Before: The land area of the earth is 57268900(29% of the surface) square miles.
After: The land area of the earth is 57,268,900(29% of the surface) square miles.
Before: Ain't no numbers in this here words, nohow, no way, Jose.
After: Ain't no numbers in this here words, nohow, no way, Jose.
Before: James was never known as 0000000007
After: James was never known as 0000000007
Before: Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.
After: Arthur Eddington wrote: I believe there are 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.
Before: $-140000±100 millions.
After: $-140,000±100 millions.
Before: 6/9/1946 was a good year for some.
After: 6/9/1946 was a good year for some.</pre>
 
=={{header|REXX}}==
The hardest part of the &nbsp; '''comma''' &nbsp; function is to locate where a useable&nbsp; ''usable'' &nbsp; number starts and ends.
<langsyntaxhighlight lang="rexx">/*REXX program addadds commas (or other chars) to a string or a number within a string.*/
@. =
@.1= "pi=3.14159265358979323846264338327950288419716939937510582097494459231"
@.2= "The author has two Z$100000000000000 Zimbabwe notes (100 trillion)."
@.3= "-in Aus$+1411.8millions"
@.4= "===US$0017440 millions=== (in 2000 dollars)"
@.5= "123.e8000 is pretty big."
@.6= "The land area of the earth is 57268900(29% of the surface) square miles."
@.7= "Ain't no numbers in this here words, nohow, no way, Jose."
@.8= "James was never known as 0000000007"
@.9= "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe."
@.10= " $-140000±100 millions."
@.11= "6/9/1946 was a good year for some."
 
do i=1 while @.i\==''; if i\==1 then say /*process each string*/
say 'before:'@.i /*show the before str*/
if i==1 then say ' after:'comma(@.i,'blank',5,,6) /*p=5, start=6*/
if i==2 then say ' after:'comma(@.i,".") /*comma=decimal point*/
if i>2 then say ' after:'comma(@.i) /*use the defaults. */
end /*j*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────COMMA subroutine────────────────────*/
comma: procedure; parse arg _,c,p,t,s /*get number and optional options*/
arg ,cU . /*get an uppercase version of C.*/
c=word(c ',', 1) /*get the commatizing char(s).*/
if cU=='BLANK' then c=' ' /*special case for a "blank" sep.*/
o=word(p 3, 1) /*get the optional period length.*/
p=abs(o) /*get the positive period length.*/
t=word(t 999999999, 1) /*get max# of "commas" to insert.*/
s=word(s 1, 1) /*get optional start position. */
 
if \datatype(p,'W') | \datatype(t,"W") | \datatype(s,'W') |,
t<1 | s<1 | p==0 | arg()>5 then return _ /*invalid options?*/
 
n do i=_'1 while @.9i\==''; #=123456789; k=0 if /*definei\==1 some handy-dandythen vars.say /*process each string.*/
say 'before──►'@.i /*show the before str.*/
 
if o<0 then do if i==1 then say ' after──►'comma(@.i, 'blank', 5, , 6) /* p=5, start=6. /*using a negative period length.*/
if i==2 then say b=verify(_,' after──►'comma(@.i, , s".") /*position of 1st blank in string /*comma=decimal point.*/
if i>2 then say ' after──►'comma(@.i) /*use the defaults. */
e=length(_) - verify(reverse(_), ' ') + 1 - p
end end/*j*/
exit else do /*usingstick a positivefork periodin lengthit, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
b=verify(n, #, "M", s) /*position of 1st useable digits.*/
comma: procedure; parse arg x,sep,period,times,start /*obtain true case arguments.*/
z=max(1, verify(n, #"0.", 'M', s))
e=verify(n, #'0', , max(1, verify(n arg ,sepU /* #"0.", 'M', s))) -uppercase p2nd arg. - 1*/
bla= ' ' /*literal to hold a "blank".*/
end
sep= word(sep ',', 1) /*define comma (string/char.)*/
 
if e>0 & b>0 then do jif sepU=e='BLANK' then sep= bla to b by -p while k<t /*commatizeallow the digsuse of 'BLANK'. */
period= word(period 3, 1) _=insert(c, _, j) /*commadefined "period" sprayto ──►be #.used*/
times= word(times 999999999, k=k+1) /*limits # changes to be /*bump commatizing. made*/
start= word(start 1 , 1) end /*jwhere to start commatizing.*/
/* [↓] various error tests. */
return _</lang>
if \datatype(period, 'W') | , /*test for a whole number. */
'''output''' when using the internal strings for input:
\datatype(times , 'W') | , /* " " " " " */
\datatype(start , 'W') | , /* " " " " " */
start <1 | , /*start can't be less then 1.*/
arg() >5 then return x /*# of args can't be > 5. */
/* [↑] some arg is invalid. */
op= period /*save the original period. */
period= abs(period) /*use the absolute value. */
n= x'.9' /*a literal string for end. */
digs= 123456789 /*the legal digits for start.*/
digsz= 1234567890 /* " " " " fin. */
digszp= 1234567890. /* " " " " fin. */
/* [↓] note: no zero in digs*/
if op<0 then do /*Negative? Treat as chars. */
beg= start /*begin at the start. */
L= length(x) /*obtain the length of X. */
fin= L - verify( reverse(x), bla) + 1 /*find the ending of the num.*/
end /* [↑] find number ending. */
else do /*Positive? Treat as numbers*/
beg= verify(n, digs, "M",start) /*find beginning of number. */
v2=max(verify(n, digszp,'M',start),1) /*end of the usable number. */
fin=verify(n, digsz, , v2) -period -1 /*adjust the ending (fin). */
end /* [↑] find ending of number*/
#= 0 /*the count of changes made. */
if beg>0 & fin>0 then /* [↓] process TIMES times*/
do j=fin to beg by -period while #<times
x= insert(sep, x, j) /*insert a comma into string.*/
#= # + 1 /*bump the count of changes. */
end /*j*/ /*(maybe no changes are made)*/
return x /*return the commatized str. */</syntaxhighlight>
{{out|output|text=&nbsp; when using the internal default inputs:}}
<pre>
before──►pi=3.14159265358979323846264338327950288419716939937510582097494459231
Line 704 ⟶ 1,647:
before──►6/9/1946 was a good year for some.
after──►6/9/1946 was a good year for some.
</pre>
 
=={{header|Scala}}==
===Java-ish version===
<syntaxhighlight lang="scala">import java.io.File
import java.util.Scanner
import java.util.regex.Pattern
 
object CommatizingNumbers extends App {
 
def commatize(s: String): Unit = commatize(s, 0, 3, ",")
 
def commatize(s: String, start: Int, step: Int, ins: String): Unit = {
if (start >= 0 && start <= s.length && step >= 1 && step <= s.length) {
val m = Pattern.compile("([1-9][0-9]*)").matcher(s.substring(start))
val result = new StringBuffer(s.substring(0, start))
if (m.find) {
val sb = new StringBuilder(m.group(1)).reverse
for (i <- step until sb.length by step) sb.insert(i, ins)
m.appendReplacement(result, sb.reverse.toString)
}
println(m.appendTail(result))
}
}
 
commatize("pi=3.14159265358979323846264338327950288419716939937510582" + "097494459231", 6, 5, " ")
commatize("The author has two Z$100000000000000 Zimbabwe notes (100 " + "trillion).", 0, 3, ".")
 
val sc = new Scanner(new File("input.txt"))
while (sc.hasNext) commatize(sc.nextLine)
}</syntaxhighlight>
 
=={{header|Swift}}==
 
{{trans|Kotlin}}
 
<syntaxhighlight lang="swift">import Foundation
 
extension String {
private static let commaReg = try! NSRegularExpression(pattern: "(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)")
 
public func commatize(start: Int = 0, period: Int = 3, separator: String = ",") -> String {
guard separator != "" else {
return self
}
 
let sep = Array(separator)
let startIdx = index(startIndex, offsetBy: start)
let matches = String.commaReg.matches(in: self, range: NSRange(startIdx..., in: self))
 
guard !matches.isEmpty else {
return self
}
 
let fullMatch = String(self[Range(matches.first!.range(at: 0), in: self)!])
let splits = fullMatch.components(separatedBy: ".")
var ip = splits[0]
 
if ip.count > period {
var builder = Array(ip.reversed())
 
for i in stride(from: (ip.count - 1) / period * period, through: period, by: -period) {
builder.insert(contentsOf: sep, at: i)
}
 
ip = String(builder.reversed())
}
 
if fullMatch.contains(".") {
var dp = splits[1]
 
if dp.count > period {
var builder = Array(dp)
 
for i in stride(from: (dp.count - 1) / period * period, through: period, by: -period) {
builder.insert(contentsOf: sep, at: i)
}
 
dp = String(builder)
}
 
ip += "." + dp
}
 
return String(prefix(start)) + String(dropFirst(start)).replacingOccurrences(of: fullMatch, with: ip)
}
}
 
let tests = [
"123456789.123456789",
".123456789",
"57256.1D-4",
"pi=3.14159265358979323846264338327950288419716939937510582097494459231",
"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",
"-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."
]
 
print(tests[0].commatize(period: 2, separator: "*"))
print(tests[1].commatize(period: 3, separator: "-"))
print(tests[2].commatize(period: 4, separator: "__"))
print(tests[3].commatize(period: 5, separator: " "))
print(tests[4].commatize(separator: "."))
 
for testCase in tests.dropFirst(5) {
print(testCase.commatize())
}</syntaxhighlight>
 
{{out}}
 
<pre>1*23*45*67*89.12*34*56*78*9
.123-456-789
5__7256.1D-4
pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).
-in Aus$+1,411.8millions
===US$0017,440 millions=== (in 2000 dollars)
123.e8000 is pretty big.
The land area of the earth is 57,268,900(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 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.
$-140,000±100 millions.
6/9/1946 was a good year for some.</pre>
 
=={{header|VBA}}==
{{trans|Phix}}
<syntaxhighlight lang="vb">Public Sub commatize(s As String, Optional sep As String = ",", Optional start As Integer = 1, Optional step As Integer = 3)
Dim l As Integer: l = Len(s)
For i = start To l
If Asc(Mid(s, i, 1)) >= Asc("1") And Asc(Mid(s, i, 1)) <= Asc("9") Then
For j = i + 1 To l + 1
If j > l Then
For k = j - 1 - step To i Step -step
s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)
l = Len(s)
Next k
Exit For
Else
If (Asc(Mid(s, j, 1)) < Asc("0") Or Asc(Mid(s, j, 1)) > Asc("9")) Then
For k = j - 1 - step To i Step -step
s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)
l = Len(s)
Next k
Exit For
End If
End If
Next j
Exit For
End If
Next i
Debug.Print s
End Sub
Public Sub main()
commatize "pi=3.14159265358979323846264338327950288419716939937510582097494459231", " ", 6, 5
commatize "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "."
commatize """-in Aus$+1411.8millions"""
commatize "===US$0017440 millions=== (in 2000 dollars)"
commatize "123.e8000 is pretty big."
commatize "The land area of the earth is 57268900(29% of the surface) square miles."
commatize "Ain't no numbers in this here words, nohow, no way, Jose."
commatize "James was never known as 0000000007"
commatize "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe."
commatize " $-140000±100 millions."
commatize "6/9/1946 was a good year for some."
End Sub</syntaxhighlight>{{out}}
<pre>pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).
"-in Aus$+1,411.8millions"
===US$0017,440 millions=== (in 2000 dollars)
123.e8000 is pretty big.
The land area of the earth is 57,268,900(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 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.
$-140,000±100 millions.
6/9/1946 was a good year for some.</pre>
 
=={{header|VBScript}}==
Adapted from the Future Basic code
<syntaxhighlight lang="vb">
function commatize( s , sep, start , stp )
if sep ="" then sep = ","
if start ="" then start = 1
if stp ="" then stp = 3
Dim i, j, k, l
l = len(s)
for i = start to l
if ( asc( mid( s, i, 1 ) ) >= asc("1") and asc( mid( s, i, 1) ) <= asc("9") ) then
for j = i + 1 to l + 1
if ( j > l ) then
for k = j - 1 - stp to i step -stp
s = mid( s, 1, k ) + sep + mid( s, k + 1, l - k + 1 )
l = len(s)
next 'k
exit for
else
if ( asc( mid( s, j, 1 ) ) < asc("0") or asc( mid( s, j, 1 ) ) > asc("9") ) then
for k = j - 1 - stp to i step -stp
s = mid( s, 1, k ) + sep + mid( s, k + 1, l - k + 1 )
l = len(s)
Next ' k
exit for
end if
end if
next 'j
exit for
end if
next '
commatize=S
end function
 
wscript.echo commatize("pi=3.14159265358979323846264338327950288419716939937510582097494459231" , " " , 6, 5 )
wscript.echo commatize("The author has two Z$100000000000000 Zimbabwe notes (100 trillion)." , "." , "", "" )
wscript.echo commatize("\'-in Aus$+1411.8millions\'" , "," , "", "" )
wscript.echo commatize("===US$0017440 millions=== (in 2000 dollars)" , "" , "", "" )
wscript.echo commatize("123.e8000 is pretty big." , "" , "", "" )
wscript.echo commatize("The land area of the earth is 57268900(29% of the surface) square miles." , "" , "", "" )
wscript.echo commatize("Ain't no numbers in this here words, nohow, no way, Jose." , "" , "", "" )
wscript.echo commatize("James was never known as 0000000007" , "" , "", "" )
wscript.echo commatize("Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.", ",", "", "" )
wscript.echo commatize(" $-140000±100 millions." , "" , "", "" )
wscript.echo commatize("6/9/1946 was a good year for some." , "" , "", "" )
</syntaxhighlight>
{{out}}
<small>
<pre>
pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).
\'-in Aus$+1,411.8millions\'
===US$0017,440 millions=== (in 2000 dollars)
123.e8000 is pretty big.
The land area of the earth is 57,268,900(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 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.
$-140,000±100 millions.
6/9/1946 was a good year for some.
</pre>
</small>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">var commatize = Fn.new { |s, start, step, sep|
var addSeps = Fn.new { |n, dp|
var lz = ""
if (!dp && n.startsWith("0") && n != "0") {
var k = n.trimStart("0")
if (k == "") k = "0"
lz = "0" * (n.count - k.count)
n = k
}
if (dp) n = n[-1..0] // invert if after decimal point
var i = n.count - step
while (i >= 1) {
n = n[0...i] + sep + n[i..-1]
i = i - step
}
if (dp) n = n[-1..0] // invert back
return lz + n
}
 
var t = s.toList
var isExponent = Fn.new { |c| "eEdDpP^∙x↑*⁰¹²³⁴⁵⁶⁷⁸⁹".contains(c) }
var acc = (start == 0) ? "" : t.toList[0...start].join()
var n = ""
var dp = false
for (j in start...t.count) {
var c = t[j].codePoints[0]
if (c >= 48 && c <= 57) {
n = n + t[j]
if (j == t.count-1) {
if (acc != "" && isExponent.call(acc[-1])) {
acc = s
} else {
acc = acc + addSeps.call(n, dp)
}
}
} else if (n != "") {
if (acc != "" && isExponent.call(acc[-1])) {
acc = s
break
} else if (t[j] != ".") {
acc = acc + addSeps.call(n, dp) + t[j..-1].join()
break
} else {
acc = acc + addSeps.call(n, dp) + t[j]
dp = true
n = ""
}
} else {
acc = acc + t[j]
}
}
 
System.print(s)
System.print(acc)
System.print()
}
 
// special version of the above which uses defaults for start, step and sep.
var commatize2 = Fn.new { |s| commatize.call(s, 0, 3, ",") }
 
commatize.call("123456789.123456789", 0, 2, "*")
commatize.call(".123456789", 0, 3, "-")
commatize.call("57256.1D-4", 0, 4, "__")
commatize.call("pi=3.14159265358979323846264338327950288419716939937510582097494459231", 0, 5, " ")
commatize.call("The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 0, 3, ".")
 
var 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."
]
 
defaults.each { |d| commatize2.call(d) }</syntaxhighlight>
 
{{out}}
<pre>
123456789.123456789
1*23*45*67*89.12*34*56*78*9
 
.123456789
.123-456-789
 
57256.1D-4
5__7256.1D-4
 
pi=3.14159265358979323846264338327950288419716939937510582097494459231
pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
 
The author has two Z$100000000000000 Zimbabwe notes (100 trillion).
The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).
 
"-in Aus$+1411.8millions"
"-in Aus$+1,411.8millions"
 
===US$0017440 millions=== (in 2000 dollars)
===US$0017,440 millions=== (in 2000 dollars)
 
123.e8000 is pretty big.
123.e8000 is pretty big.
 
The land area of the earth is 57268900(29% of the surface) square miles.
The land area of the earth is 57,268,900(29% of the surface) square miles.
 
Ain't no numbers in this here words, nohow, no way, Jose.
Ain't no numbers in this here words, nohow, no way, Jose.
 
James was never known as 0000000007
James was never known as 0000000007
 
Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.
Arthur Eddington wrote: I believe there are 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.
 
$-140000±100 millions.
$-140,000±100 millions.
 
6/9/1946 was a good year for some.
6/9/1946 was a good year for some.
 
</pre>
9,485

edits