Getting the number of decimal places: Difference between revisions
Content added Content deleted
Drkameleon (talk | contribs) (added Arturo) |
|||
Line 374: | Line 374: | ||
else return (str.substring(str.indexOf('.')).length() - 1); |
else return (str.substring(str.indexOf('.')).length() - 1); |
||
}</syntaxhighlight> |
}</syntaxhighlight> |
||
=={{header|jq}}== |
|||
The current (March 2023) official releases of jq, gojq, fq, and jaq cannot be relied upon |
|||
to preserve the literal form of numbers, and in particular they drop the |
|||
final 0 of `12.3450` when presented as a number. However, the current "master" version of jq retains |
|||
the literal form of numbers. Accordingly, both the numeric and the string forms of 12.3450 are included in the suite of test |
|||
cases, and two sets of results are presented below. |
|||
<syntaxhighlight lang=jq> |
|||
def number_decimal_digits: |
|||
. as $in |
|||
| def nil: . == null or . == ""; |
|||
def nodecimal: # e.g. 12 or 12e-2 |
|||
capture("^[-+]?[0-9]*([eE](?<sign>[-+]?)(?<p>[0-9]+))?$") |
|||
| if .sign|nil then 0 |
|||
elif .p|nil then "internal error: \($in)"|error |
|||
else .p|tonumber |
|||
end; |
|||
tostring |
|||
| nodecimal |
|||
// capture("^[-+]?[0-9]*[.](?<d>[0-9]+)([eE](?<sign>[-+]?)(?<p>[0-9]+))?$") # has decimal |
|||
// null |
|||
| if type == "number" then . |
|||
elif not then 0 |
|||
elif .d|nil then 0 |
|||
elif (.sign|nil) and .p == null then .d|length |
|||
elif (.sign|nil) or .sign == "+" then [0, (.d|length) - (.p|tonumber)] | max |
|||
elif .sign == "-" then (.d|length) + (.p|tonumber) |
|||
else "internal error: \($in)"|error |
|||
end ; |
|||
def examples: |
|||
[12.345, 3], |
|||
[12.3450, 4], |
|||
["12.3450", 4], |
|||
[1e-2, 2], |
|||
[1.23e2, 0]; |
|||
def task: |
|||
examples |
|||
| (first|number_decimal_digits) as $d |
|||
| if $d == last then empty |
|||
else "\(first) has \(last) decimal places but the computed value is \($d)" |
|||
end; |
|||
task, "Bye." |
|||
</syntaxhighlight> |
|||
{{output}} |
|||
Using gojq: |
|||
<pre> |
|||
12.345 has 4 decimal places but the computed value is 3 |
|||
Bye. |
|||
</pre> |
|||
Using jq post-1.6: |
|||
<pre> |
|||
Bye. |
|||
</pre> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |