Number names: Difference between revisions

Content deleted Content added
Peak (talk | contribs)
jq
Line 1,946:
 
print to.english 1234567 ; one million two hundred thirty four thousand five hundred sixty seven</lang>
 
=={{header|jq}}==
<lang jq># Adapted from the go version.
# Tested with jq 1.4
#
# say/0 as defined here supports positive and negative integers within
# the range of accuracy of jq, or up to the quintillions, whichever is
# less. As of jq version 1.4, jq's integer accuracy is about 10^16.
 
# In newer versions of jq, various iterators are available, but
# for compatibility with jq version 1.4, we here use recurse(f),
# which generates ., f, f|f, f|f|f, ... until some condition is met.
# loop(f) captures the last-generated value if there is any:
def loop(f): [recurse(f)] | .[length-1];
 
def say:
[ "", "one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] as $small
| ["ones", "ten", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"] as $tens
| ["thousand", "million", "billion",
"trillion", "quadrillion", "quintillion"] as $illions
 
| if . == 0 then "zero"
elif . < 0 then "minus " + (-(.) | say)
elif . < 20 then $small[.]
elif . < 100 then
$tens[./10|floor] as $t
| (. % 10)
| if . > 0 then ($t + " " + $small[.]) else $t end
elif . < 1000 then
($small[./100|floor] + " hundred") as $h
| (. % 100)
| if . > 0 then $h + " and " + (say) else $h end
else
# Handle values larger than 1000 by considering
# the rightmost three digits separately from the rest:
((. % 1000)
| if . == 0 then ""
elif . < 100 then "and " + say
else say
end) as $sx
 
# Iteratively update the state variable [$i, $n, $sx]
# where: $i is a counter (initially 0),
# $n is divided by 1000 at each iteration, and
# $sx is the incrementally constructed answer, a string.
| [ 0, ., $sx] # initial state
| loop(if .[1] == 0 then empty
else
.[0] as $i
| (.[1] / 1000 | floor) as $n
| .[2] as $sx
| ($n % 1000) as $p
# the next state:
| [ $i + 1,
$n,
if $p > 0 then
(($p | say) + " " + $illions[$i]) as $ix
| if $sx != "" then $ix + ", " + $sx
else $ix
end
else $sx
end
]
end)[2] # extract the string
end;
 
say</lang>
Transcript (input followed by output):
<lang jq>0
"zero"
-0
"zero"
111
"one hundred and eleven"
1230000
"one million, two hundred and thirty thousand"
123456
"one hundred and twenty three thousand, four hundred and fifty six"
123456789
"one hundred and twenty three million, four hundred and fifty six thousand, seven hundred and eighty nine"
-123000000123
"minus one hundred and twenty three billion, one hundred and twenty three"
12345678912345678
"twelve quadrillion, three hundred and forty five trillion, six hundred and seventy eight billion, nine hundred and twelve million, three hundred and forty five thousand, six hundred and seventy eight"
</jq>
 
=={{header|Lua}}==