Commatizing numbers: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(Added 11l)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(6 intermediate revisions by 4 users not shown)
Line 85:
{{trans|Nim}}
 
<langsyntaxhighlight lang="11l">F commatize(s, period = 3, sep = ‘,’)
V m = re:‘(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)’.search(s)
I !m
Line 133:
 
L(test) tests[5..]
print(commatize(test))</langsyntaxhighlight>
 
{{out}}
Line 154:
 
=={{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 240:
newline ) );
print( ( COMMATIZE " $-140000±100 millions.", newline ) );
print( ( COMMATIZE "6/9/1946 was a good year for some.", newline ) )</langsyntaxhighlight>
{{out}}
<pre>
Line 257:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
static string[] inputs = {
"pi=3.14159265358979323846264338327950288419716939937510582097494459231",
Line 306:
}
}
</syntaxhighlight>
</lang>
 
=={{header|D}}==
Better to have more tests than more features.
<langsyntaxhighlight lang="d">import std.stdio, std.regex, std.range;
 
auto commatize(in char[] txt, in uint start=0, in uint step=3,
Line 364:
foreach (const line; "commatizing_numbers_using_defaults.txt".File.byLine)
line.commatize.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
Line 382:
{{libheader| system.StrUtils}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Commatizing_numbers;
 
Line 472:
Writeln(commatize(TESTS[i], 0, 3, ','));
readln;
end.</langsyntaxhighlight>
 
=={{header|Factor}}==
{{works with|Factor|0.99 2020-01-23}}
<langsyntaxhighlight lang="factor">USING: accessors grouping io kernel math regexp sequences
splitting strings unicode ;
 
Line 509:
" $-140000±100 millions."
"6/9/1946 was a good year for some."
} [ commatize print ] each</langsyntaxhighlight>
{{out}}
<pre>
Line 529:
{{trans|VBA}}
{{trans|Phix}}
<langsyntaxhighlight 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
Line 568:
commatize("6/9/1946 was a good year for some.")
 
Sleep</langsyntaxhighlight>
{{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}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 651 ⟶ 721:
fmt.Println(commatize(test, 0, 3, ","))
}
}</langsyntaxhighlight>
 
{{out}}
Line 676 ⟶ 746:
{{Works with|GHC|8.6.5}}
 
<langsyntaxhighlight lang="haskell">#!/usr/bin/env runhaskell
 
import Control.Monad (forM_)
Line 744 ⟶ 814:
putStrLn str
putStrLn $ commatize str by sep
putStrLn ""</langsyntaxhighlight>
{{out}}
<pre>
Line 785 ⟶ 855:
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 805 ⟶ 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 830 ⟶ 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 872 ⟶ 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 885 ⟶ 955:
$-140,000±100 millions.
6/9/1946 was a good year for some.</pre>
 
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]]'''
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq.'''
<syntaxhighlight lang="jq">
def commatize($s; $start; $step; $sep):
 
def isExponent($c): "eEdDpP^∙x↑*⁰¹²³⁴⁵⁶⁷⁸⁹" | index($c);
def rev: explode|reverse|implode;
def addSeps($n; $dp):
{ $n, lz: "" }
| if ($dp|not) and ($n|startswith("0")) and $n != "0"
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}}
<langsyntaxhighlight lang="julia">input = [
["pi=3.14159265358979323846264338327950288419716939937510582097494459231", " ", 5],
[raw"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "."],
Line 917 ⟶ 1,084:
println(commatize(tst))
end
</langsyntaxhighlight> {{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).
Line 932 ⟶ 1,099:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.4-3
 
val r = Regex("""(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)""")
Line 989 ⟶ 1,156:
println(tests[4].commatize(sep = "."))
for (test in tests.drop(5)) println(test.commatize())
}</langsyntaxhighlight>
 
{{out}}
Line 1,013 ⟶ 1,180:
This is a translation of the Kotlin (and Go) algorithm with some modifications.
 
<langsyntaxhighlight Nimlang="nim">import re
import strutils
 
Line 1,081 ⟶ 1,248:
 
for n in 5..Tests.high:
echo Tests[n].commatize()</langsyntaxhighlight>
 
{{out}}
Line 1,101 ⟶ 1,268:
=={{header|Perl}}==
Displaying before/after only when changes applied.
<langsyntaxhighlight lang="perl">@input = (
['pi=3.14159265358979323846264338327950288419716939937510582097494459231', ' ', 5],
['The author has two Z$100000000000000 Zimbabwe notes (100 trillion).', '.'],
Line 1,138 ⟶ 1,305:
$c =~ s/$sep$//;
return reverse $c;
}</langsyntaxhighlight>
{{out}}
<pre>pi=3.14159265358979323846264338327950288419716939937510582097494459231
Line 1,164 ⟶ 1,331:
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
<!--<langsyntaxhighlight Phixlang="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>
Line 1,195 ⟶ 1,362:
<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>
<!--</langsyntaxhighlight>-->
{{Out}}
<pre>
Line 1,212 ⟶ 1,379:
 
=={{header|Python}}==
<syntaxhighlight lang="python">
<lang Python>
import re as RegEx
 
Line 1,250 ⟶ 1,417:
print ( Commatize( "␢␢␢$-140000±100 millions." ))
print ( Commatize( "6/9/1946 was a good year for some." ))
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Line 1,261 ⟶ 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 1,335 ⟶ 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" perl6line>for ('pi=3.14159265358979323846264338327950288419716939937510582097494459231', {:6at, :5by, :ins(' ')}),
('The author has two Z$100000000000000 Zimbabwe notes (100 trillion).', {:ins<.>}),
'-in Aus$+1411.8millions',
Line 1,358 ⟶ 1,525:
$s.subst: :continue($at), :1st, / <[1..9]> <[0..9]>* /,
*.flip.comb(/<{ ".**1..$by" }>/).join($ins).flip;
}</langsyntaxhighlight>
{{out}}
<pre>Before: pi=3.14159265358979323846264338327950288419716939937510582097494459231
Line 1,385 ⟶ 1,552:
=={{header|REXX}}==
The hardest part of the &nbsp; '''comma''' &nbsp; function is to locate where a &nbsp; ''usable'' &nbsp; number starts and ends.
<langsyntaxhighlight lang="rexx">/*REXX program adds commas (or other chars) to a string or a number within a string.*/
@. =
@.1= "pi=3.14159265358979323846264338327950288419716939937510582097494459231"
Line 1,445 ⟶ 1,612:
#= # + 1 /*bump the count of changes. */
end /*j*/ /*(maybe no changes are made)*/
return x /*return the commatized str. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the internal default inputs:}}
<pre>
Line 1,484 ⟶ 1,651:
=={{header|Scala}}==
===Java-ish version===
<langsyntaxhighlight Scalalang="scala">import java.io.File
import java.util.Scanner
import java.util.regex.Pattern
Line 1,510 ⟶ 1,677:
val sc = new Scanner(new File("input.txt"))
while (sc.hasNext) commatize(sc.nextLine)
}</langsyntaxhighlight>
 
=={{header|Swift}}==
Line 1,516 ⟶ 1,683:
{{trans|Kotlin}}
 
<langsyntaxhighlight Swiftlang="swift">import Foundation
 
extension String {
Line 1,595 ⟶ 1,762:
for testCase in tests.dropFirst(5) {
print(testCase.commatize())
}</langsyntaxhighlight>
 
{{out}}
Line 1,616 ⟶ 1,783:
=={{header|VBA}}==
{{trans|Phix}}
<langsyntaxhighlight 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
Line 1,654 ⟶ 1,821:
commatize " $-140000±100 millions."
commatize "6/9/1946 was a good year for some."
End Sub</langsyntaxhighlight>{{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).
Line 1,666 ⟶ 1,833:
$-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}}==
<langsyntaxhighlight ecmascriptlang="wren">var commatize = Fn.new { |s, start, step, sep|
var addSeps = Fn.new { |n, dp|
var lz = ""
Line 1,746 ⟶ 1,979:
]
 
defaults.each { |d| commatize2.call(d) }</langsyntaxhighlight>
 
{{out}}
9,476

edits