Numeric separator syntax: Difference between revisions

No edit summary
Line 337:
Underscores allowed in floating point number: 0.0014400
Underscores allowed in floating point exponent: 0.0000144
</pre>
 
=={{header|jq}}==
'''Works with jq and gojq, the C and Go implementations of jq'''
 
jq does not support any separator syntax for numbers, and does not provide any built-in
filters for formatting them with a thousands-separator, or for "decommatizing" strings
that could be interpreted as numbers.
 
The following definitions, however, can be used to commatize integers, whether
expressed as strings or as (JSON) numbers. Exponential notation is
supported, as illustrated by some of the examples below.
 
Note that since both gojq and sufficiently recent versions of jq support indefinitely large
numeric integers, some of the examples assume such support.
<syntaxhighlight lang=jq>
# The def of _nwise/1 can be omitted if using the C implementation of jq.
def _nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;
 
# commatize/0 and commatize/1 are intended for integers or integer-valued strings,
# where integers of the form [-]?[0-9]*[Ee][+]?[0-9]+ are allowed.
# Notice that a leading '+' is disallowed, as is an exponent of the form '-0'.
# Output: a string
def commatize($comma):
def c: [explode | reverse | _nwise(3) | reverse | implode] | reverse | join($comma);
def e: "unable to commatize: " + tostring | error;
 
if type == "string"
then if test("^[0-9]+$") then c
elif test("^-[0-9]+$") then "-" + .[1:] | c
else (capture("(?<s>[-])?(?<i>[0-9]*)[Ee][+]?(?<e>[0-9]+)$") // null)
| if .
then if .i == "" then .i="1" else . end
| .s |= (if . = null then "" else . end)
| .s + ((.i + (.e|tonumber) * "0") | c)
else e
end
end
elif type == "number" and . == floor
then if . >= 0
then tostring|commatize($comma)
else "-" + (-. | tostring | commatize($comma) )
end
else e
end;
 
def commatize:
commatize(",");
</syntaxhighlight>
'''Examples'''
<syntaxhighlight lang=jq>
[ 1e6, 1e9, 123456789, -123456789012, 1e20, "e20", -10e19, 123456789123456789123456789 ] as $nums
| [",", ".", " ", "*"] as $seps
| range(0;$nums|length) as $i
| $nums[$i] | commatize($seps[$i] // ",")
</syntaxhighlight>
{{output}}
<pre>
1,000,000
1.000.000.000
123 456 789
-123*456*789*012
100,000,000,000,000,000,000
100,000,000,000,000,000,000
-100,000,000,000,000,000,000
123,456,789,123,456,789,123,456,789
</pre>
 
2,449

edits