Names to numbers: Difference between revisions

m
(→‎{{header|Perl}}: extensively refactored, various enhancements)
m (→‎{{header|Wren}}: Minor tidy)
 
(27 intermediate revisions by 12 users not shown)
Line 7:
* [[Number names]] — the reverse operation.
 
=={{header|D11l}}==
{{trans|Nim}}
This uses the D module from the Number names task.
{{trans|Python}}
<lang d>import std.stdio, std.array, std.string, std.algorithm, std.bigint,
std.range, number_names;
 
<syntaxhighlight lang="11l">V Names = [‘one’ = Int64(1),
BigInt bigIntFromWords(in string num)
‘two’ = 2,
in {
‘three’ = 3,
assert(!num.empty);
‘four’ = 4,
} body {
‘five’ = 5,
auto words = num.replace(",", "").replace(" and ", " ")
‘six’ = .replace("-"6, " ").split;
‘seven’ = 7,
‘eight’ = 8,
‘nine’ = 9,
‘ten’ = 10,
‘eleven’ = 11,
‘twelve’ = 12,
‘thirteen’ = 13,
‘fourteen’ = 14,
‘fifteen’ = 15,
‘sixteen’ = 16,
‘seventeen’ = 17,
‘eighteen’ = 18,
‘nineteen’ = 19,
‘twenty’ = 20,
‘thirty’ = 30,
‘forty’ = 40,
‘fifty’ = 50,
‘sixty’ = 60,
‘seventy’ = 70,
‘eighty’ = 80,
‘ninety’ = 90,
‘hundred’ = 100,
‘thousand’ = 1000,
‘million’ = 1000000,
‘billion’ = 1000000000,
‘trillion’ = 1000000000000,
‘quadrillion’ = 1000000000000000,
‘quintillion’ = 1000000000000000000]
 
V Zeros = [‘zero’, ‘nought’, ‘nil’, ‘none’, ‘nothing’]
immutable sign = (words[0] == "minus") ? -1 : +1;
if (sign == -1)
words = words[1 .. $];
 
F nameToNum(name)
BigInt bsmall, total;
V text = name.lowercase()
foreach (const word; words) {
V isNegative = text.starts_with(‘minus ’)
if (small.canFind(word)) {
I isNegative
bsmall += small.countUntil(word);
text = text[6..]
} else if (tens.canFind(word)) {
I text.starts_with(‘a’)
bsmall += tens.countUntil(word) * 10;
text = ‘one’text[1..]
} else if (word == "hundred") {
V words = text.split(re:‘,|-| and | ’).filter(w -> !w.empty)
bsmall *= 100;
I words.len == 1 & words[0] C Zeros
} else if (word == "thousand") {
R Int64(0)
total += bsmall * 1000;
bsmall = 0;
} else if (huge.canFind(word)) {
total += bsmall * BigInt(1000) ^^ huge.countUntil(word);
bsmall = 0;
} else {
immutable msg = format("Don't understand %s part of %s",
word, num);
throw new Exception(msg);
}
}
 
V multiplier = Int64(1)
return sign * (total + bsmall);
V sum = Int64(0)
}
L(i) (words.len - 1 .< -1).step(-1)
V num = Names.get(words[i], 0)
I num >= 1000
multiplier = num
I i == 0
sum += multiplier
E I num >= 100
multiplier *= 100
I i == 0
sum += multiplier
E
sum += num * multiplier
 
R I isNegative {-sum} E sum
void main() {
foreach (immutable n; iota(-10000, 10000, 17))
assert(n == n.BigInt.spellBigInt.bigIntFromWords);
 
V names = [
foreach (immutable p; 0 .. 20) {
‘none’,
auto n = 13.BigInt ^^ p;
‘one’,
assert(n == n.spellBigInt.bigIntFromWords);
‘twenty-five’,
}
‘minus one hundred and seventeen’,
‘hundred and fifty-six’,
‘minus two thousand two’,
‘nine thousand, seven hundred, one’,
‘minus six hundred and twenty six thousand, eight hundred and fourteen’,
‘four million, seven hundred thousand, three hundred and eighty-six’,
‘fifty-one billion, two hundred and fifty-two million, seventeen thousand, one hundred eighty-four’,
‘two hundred and one billion, twenty-one million, two thousand and one’,
‘minus three hundred trillion, nine million, four hundred and one thousand and thirty-one’,
‘seventeen quadrillion, one hundred thirty-seven’,
‘a quintillion, eight trillion and five’,
‘minus nine quintillion, two hundred and twenty-three quadrillion, three hundred and seventy-two trillion, thirty-six billion, eight hundred and fifty-four million, seven hundred and seventy-five thousand, eight hundred and eight’]
 
L(name) names
writeln("This shows <==> for a successful round trip, " ~
print(‘#20’.format(nameToNum(name))‘ = ’name)</syntaxhighlight>
" <??> otherwise:");
foreach (immutable n; [0, -3, 5, -7, 11, -13, 17, -19, 23, -29]) {
const txt = n.BigInt.spellBigInt;
auto num = txt.bigIntFromWords;
writefln("%+4d <%s> %s", n, (n == num) ? "==" : "??", txt);
}
writeln;
 
long n = 201_021_002_001;
while (n) {
const txt = n.BigInt.spellBigInt;
auto num = txt.bigIntFromWords;
writefln("%12d <%s> %s", n, (n == num) ? "==" : "??", txt);
n /= -10;
}
const txt = n.BigInt.spellBigInt;
auto num = txt.bigIntFromWords;
writefln("%12d <%s> %s", n, (n == num) ? "==" : "??", txt);
}</lang>
{{out}}
<pre>
<pre>This shows <==> for a successful round trip, <??> otherwise:
0 = none
+0 <==> zero
1 = one
-3 <==> minus three
+5 <= 25 => twenty-five
-7117 <==> minus sevenone hundred and seventeen
156 = hundred and fifty-six
+11 <==> eleven
-132002 <==> minus thirteentwo thousand two
9701 = nine thousand, seven hundred, one
+17 <==> seventeen
-626814 = minus six hundred and twenty six thousand, eight hundred and fourteen
-19 <==> minus nineteen
4700386 = four million, seven hundred thousand, three hundred and eighty-six
+23 <==> twenty-three
51252017184 = fifty-one billion, two hundred and fifty-two million, seventeen thousand, one hundred eighty-four
-29 <==> minus twenty-nine
201021002001 = two hundred and one billion, twenty-one million, two thousand and one
 
201021002001 <==> two hundred and-300000009401031 one= minus three hundred billiontrillion, twenty-onenine million, twofour hundred and one thousand, and thirty-one
17000000000000137 = seventeen quadrillion, one hundred thirty-seven
-20102100200 <==> minus twenty billion, one hundred and two million, one hundred thousand, and two hundred
1000008000000000005 = a quintillion, eight trillion and five
2010210020 <==> two billion, ten million, two hundred and ten thousand, and twenty
-2010210029223372036854775808 <==> minus nine quintillion, two hundred and onetwenty-three quadrillion, three hundred and seventy-two trillion, thirty-six billion, eight hundred and fifty-four million, twentyseven hundred and seventy-onefive thousand, eight hundred and twoeight
</pre>
20102100 <==> twenty million, one hundred and two thousand, and one hundred
-2010210 <==> minus two million, ten thousand, two hundred and ten
201021 <==> two hundred and one thousand, and twenty-one
-20102 <==> minus twenty thousand, one hundred and two
2010 <==> two thousand, and ten
-201 <==> minus two hundred and one
20 <==> twenty
-2 <==> minus two
0 <==> zero</pre>
 
=={{header|Common Lisp}}==
A counterpart to (format t "~R" ...).
<langsyntaxhighlight Lisplang="lisp">(defpackage number-names
(:use cl))
 
Line 300 ⟶ 310:
(format t "~a => ~a => ~a~%" number word (parse word))))
test-numbers))
(values))</langsyntaxhighlight>
Running the test procedure:
<langsyntaxhighlight lang="none">CL-USER> (number-names::test)
number => (format t "~R" number) => (parse (format t "~R" number))
0 => zero => 0
Line 327 ⟶ 337:
-2 => negative two => -2
0 => zero => 0
; No value</langsyntaxhighlight>
 
=={{header|D}}==
This uses the D module from the Number names task.
{{trans|Python}}
<syntaxhighlight lang="d">import std.stdio, std.array, std.string, std.algorithm, std.bigint,
std.range, number_names;
 
BigInt bigIntFromWords(in string num)
in {
assert(!num.empty);
} body {
auto words = num.replace(",", "").replace(" and ", " ")
.replace("-", " ").split;
 
immutable sign = (words[0] == "minus") ? -1 : +1;
if (sign == -1)
words = words[1 .. $];
 
BigInt bsmall, total;
foreach (const word; words) {
if (small.canFind(word)) {
bsmall += small.countUntil(word);
} else if (tens.canFind(word)) {
bsmall += tens.countUntil(word) * 10;
} else if (word == "hundred") {
bsmall *= 100;
} else if (word == "thousand") {
total += bsmall * 1000;
bsmall = 0;
} else if (huge.canFind(word)) {
total += bsmall * BigInt(1000) ^^ huge.countUntil(word);
bsmall = 0;
} else {
immutable msg = format("Don't understand %s part of %s",
word, num);
throw new Exception(msg);
}
}
 
return sign * (total + bsmall);
}
 
void main() {
foreach (immutable n; iota(-10000, 10000, 17))
assert(n == n.BigInt.spellBigInt.bigIntFromWords);
 
foreach (immutable p; 0 .. 20) {
auto n = 13.BigInt ^^ p;
assert(n == n.spellBigInt.bigIntFromWords);
}
 
writeln("This shows <==> for a successful round trip, " ~
" <??> otherwise:");
foreach (immutable n; [0, -3, 5, -7, 11, -13, 17, -19, 23, -29]) {
const txt = n.BigInt.spellBigInt;
auto num = txt.bigIntFromWords;
writefln("%+4d <%s> %s", n, (n == num) ? "==" : "??", txt);
}
writeln;
 
long n = 201_021_002_001;
while (n) {
const txt = n.BigInt.spellBigInt;
auto num = txt.bigIntFromWords;
writefln("%12d <%s> %s", n, (n == num) ? "==" : "??", txt);
n /= -10;
}
const txt = n.BigInt.spellBigInt;
auto num = txt.bigIntFromWords;
writefln("%12d <%s> %s", n, (n == num) ? "==" : "??", txt);
}</syntaxhighlight>
{{out}}
<pre>This shows <==> for a successful round trip, <??> otherwise:
+0 <==> zero
-3 <==> minus three
+5 <==> five
-7 <==> minus seven
+11 <==> eleven
-13 <==> minus thirteen
+17 <==> seventeen
-19 <==> minus nineteen
+23 <==> twenty-three
-29 <==> minus twenty-nine
 
201021002001 <==> two hundred and one billion, twenty-one million, two thousand, and one
-20102100200 <==> minus twenty billion, one hundred and two million, one hundred thousand, and two hundred
2010210020 <==> two billion, ten million, two hundred and ten thousand, and twenty
-201021002 <==> minus two hundred and one million, twenty-one thousand, and two
20102100 <==> twenty million, one hundred and two thousand, and one hundred
-2010210 <==> minus two million, ten thousand, two hundred and ten
201021 <==> two hundred and one thousand, and twenty-one
-20102 <==> minus twenty thousand, one hundred and two
2010 <==> two thousand, and ten
-201 <==> minus two hundred and one
20 <==> twenty
-2 <==> minus two
0 <==> zero</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Generics.Collections}}
{{libheader| System.Math}}
{{Trans|Kotlin}}
<syntaxhighlight lang="delphi">
program Names_to_numbers;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
System.Generics.Collections,
System.Math;
 
function CreateMap: TDictionary<string, Int64>;
const
smallies: array[1..19] of string = ('one', 'two', 'three', 'four', 'five',
'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen',
'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen');
tens: array[2..9] of string = ('twenty', 'thirty', 'forty', 'fifty', 'sixty',
'seventy', 'eighty', 'ninety');
maxies: array[1..6] of string = ('thousand', 'million', 'billion', 'trillion',
'quadrillion', 'quintillion');
var
i: Integer;
begin
Result := TDictionary<string, Int64>.Create();
for i := 1 to 19 do
Result.Add(smallies[i], i);
 
for i := 2 to 9 do
Result.Add(tens[i], i * 10);
 
for i := 1 to 6 do
Result.Add(maxies[i], Trunc(IntPower(10, i * 3)));
 
Result.Add('hundred', 100);
end;
 
const
zeros = '"zero","nought","nil","none","nothing"';
MIN_INT64 = -9223372036854775808;
 
var
Names: TDictionary<string, Int64>;
 
function nameToNum(name: string): Int64;
var
Text, w: string;
IsNegative: Boolean;
words: TArray<string>;
size: integer;
multiplier, lastNum, sum, num: Int64;
i: Integer;
begin
Text := name.trim().ToLower();
IsNegative := Text.startsWith('minus ');
if (IsNegative) then
Text := Text.Substring(6);
 
if (Text.startsWith('a ')) then
Text := 'one' + Text.Substring(1);
words := Text.split([',', '-', ' and ', ' ']);
 
size := Length(words);
if ((size = 1) and (zeros.indexOf(words[0].QuotedString('"')) > -1)) then
exit(0);
 
multiplier := 1;
lastNum := 0;
sum := 0;
 
for i := size - 1 downto 0 do
begin
w := words[i];
if w.Trim.IsEmpty then
Continue;
 
if not Names.ContainsKey(w) then
raise EArgumentException.Create(w + ' is not a valid number');
 
num := Names[w];
 
if (num = lastNum) then
raise EArgumentException.Create(name + ' is not a well formed numeric string')
else if (num >= 1000) then
begin
if (lastNum >= 100) then
raise EArgumentException.Create(name + ' is not a well formed numeric string');
multiplier := num;
if (i = 0) then
sum := sum + multiplier;
end
else if (num >= 100) then
begin
multiplier := multiplier * 100;
if (i = 0) then
sum := sum + multiplier
end
else if (num >= 20) then
begin
if (lastNum >= 10) and (lastNum <= 90) then
raise EArgumentException.Create(name + ' is not a well formed numeric string');
sum := sum + num * multiplier;
end
else
begin
if (lastNum >= 1) and (lastNum <= 90) then
raise EArgumentException.Create(name + ' is not a well formed numeric string');
sum := sum + num * multiplier;
end;
 
lastNum := num;
end;
 
if (IsNegative and (sum = -sum)) then
exit(MIN_INT64)
else if (sum < 0) then
raise EArgumentException.Create(name + ' is outside the range of a Long integer');
 
if (IsNegative) then
Result := -sum
else
result := sum;
end;
 
const
TestCases: array[0..14] of string = ('none', 'one', 'twenty-five',
'minus one hundred and seventeen', 'hundred and fifty-six',
'minus two thousand two', 'nine thousand, seven hundred, one',
'minus six hundred and twenty six thousand, eight hundred and fourteen',
'four million, seven hundred thousand, three hundred and eighty-six',
'fifty-one billion, two hundred and fifty-two million, seventeen thousand, one hundred eighty-four',
'two hundred and one billion, twenty-one million, two thousand and one',
'minus three hundred trillion, nine million, four hundred and one thousand and thirty-one',
'seventeen quadrillion, one hundred thirty-seven',
'a quintillion, eight trillion and five',
'minus nine quintillion, two hundred and twenty-three quadrillion, three hundred and seventy-two trillion, thirty-six billion, eight hundred and fifty-four million, seven hundred and seventy-five thousand, eight hundred and eight');
 
var
name: string;
 
begin
Names := CreateMap;
 
for name in TestCases do
Writeln(nameToNum(name): 20, ' = ', name);
 
Names.free;
Readln;
end.</syntaxhighlight>
{{out}}
<pre> 0 = none
1 = one
25 = twenty-five
-117 = minus one hundred and seventeen
156 = hundred and fifty-six
-2002 = minus two thousand two
9701 = nine thousand, seven hundred, one
-626814 = minus six hundred and twenty six thousand, eight hundred and fourteen
4700386 = four million, seven hundred thousand, three hundred and eighty-six
51252017184 = fifty-one billion, two hundred and fifty-two million, seventeen thousand, one hundred eighty-four
201021002001 = two hundred and one billion, twenty-one million, two thousand and one
-300000009401031 = minus three hundred trillion, nine million, four hundred and one thousand and thirty-one
17000000000000137 = seventeen quadrillion, one hundred thirty-seven
1000008000000000005 = a quintillion, eight trillion and five
-9223372036854775808 = minus nine quintillion, two hundred and twenty-three quadrillion, three hundred and seventy-two trillion, thirty-six billion, eight hundred and fifty-four million, seven hundred and seventy-five thousand, eight hundred and eight</pre>
=={{header|Factor}}==
This solution parses number names in the same format that Factor's existing <code>number>text</code> word outputs. Meaning that for numbers under 10^66, <code>number>text</code> and <code>text>number</code> ought to be inverses of each other.
<syntaxhighlight lang="factor">USING: arrays formatting grouping kernel math math.functions
math.parser multiline peg peg.ebnf sequences sequences.deep ;
 
! Make sure a number is monotonically decreasing.
! So "one hundred and three" is valid but
! "three and one hundred" is not.
 
: check-natural ( seq -- )
[ > ] monotonic? [ "Invalid number." throw ] unless ;
 
 
! Parse number names with Factor's EBNF-like DSL.
 
EBNF: text>number [=[
one = "one"~ => [[ 1 ]]
two = "two"~ => [[ 2 ]]
three = "three"~ => [[ 3 ]]
four = "four"~ => [[ 4 ]]
five = "five"~ => [[ 5 ]]
six = "six"~ => [[ 6 ]]
seven = "seven"~ => [[ 7 ]]
eight = "eight"~ => [[ 8 ]]
nine = "nine"~ => [[ 9 ]]
ten = "ten"~ => [[ 10 ]]
eleven = "eleven"~ => [[ 11 ]]
twelve = "twelve"~ => [[ 12 ]]
thirteen = "thirteen"~ => [[ 13 ]]
fourteen = "fourteen"~ => [[ 14 ]]
fifteen = "fifteen"~ => [[ 15 ]]
sixteen = "sixteen"~ => [[ 16 ]]
seventeen = "seventeen"~ => [[ 17 ]]
eighteen = "eighteen"~ => [[ 18 ]]
nineteen = "nineteen"~ => [[ 19 ]]
twenty = "twenty"~ => [[ 20 ]]
thirty = "thirty"~ => [[ 30 ]]
forty = "forty"~ => [[ 40 ]]
fifty = "fifty"~ => [[ 50 ]]
sixty = "sixty"~ => [[ 60 ]]
seventy = "seventy"~ => [[ 70 ]]
eighty = "eighty"~ => [[ 80 ]]
ninety = "ninety"~ => [[ 90 ]]
hundred = "hundred"~ => [[ 100 ]]
thousand = "thousand"~ => [[ 1000 ]]
million = "million"~ => [[ 6 10^ ]]
billion = "billion"~ => [[ 9 10^ ]]
trillion = "trillion"~ => [[ 12 10^ ]]
 
quadrillion = "quadrillion"~ => [[ 15 10^ ]]
quintillion = "quintillion"~ => [[ 18 10^ ]]
sextillion = "sextillion"~ => [[ 21 10^ ]]
septillion = "septillion"~ => [[ 24 10^ ]]
octillion = "octillion"~ => [[ 27 10^ ]]
nonillion = "nonillion"~ => [[ 30 10^ ]]
decillion = "decillion"~ => [[ 33 10^ ]]
undecillion = "undecillion"~ => [[ 36 10^ ]]
 
duodecillion = "duodecillion"~ => [[ 39 10^ ]]
tredecillion = "tredecillion"~ => [[ 42 10^ ]]
quattuordecillion = "quattuordecillion"~ => [[ 45 10^ ]]
quindecillion = "quindecillion"~ => [[ 48 10^ ]]
sexdecillion = "sexdecillion"~ => [[ 51 10^ ]]
septendecillion = "septendecillion"~ => [[ 54 10^ ]]
octodecillion = "octodecillion"~ => [[ 57 10^ ]]
novemdecillion = "novemdecillion"~ => [[ 60 10^ ]]
vigintillion = "vigintillion"~ => [[ 63 10^ ]]
 
name = vigintillion|novemdecillion|octodecillion|
septendecillion|sexdecillion|quindecillion|
quattuordecillion|tredecillion|duodecillion|
undecillion|decillion|nonillion|octillion|
septillion|sextillion|quintillion|quadrillion|
trillion|billion|million|thousand|hundred|ninety|
eighty|seventy|sixty|fifty|forty|thirty|twenty|
nineteen|eighteen|seventeen|sixteen|fifteen|
fourteen|thirteen|twelve|eleven|ten|nine|eight|
seven|six|five|four|three|two|one
 
ws = [\n\t\r ]* => [[ drop ignore ]]
dual = name "-"~ name => [[ sum ]]
atom = dual|name
atoms = (ws atom ws)+ => [[ product ]]
compound = atoms "and"~ ws atom ws name ws
=> [[ first3 swap over [ * ] 2bi@ 2array ]]
simple = atoms "and"~ ws atom ws
basic = "and"~ ws atom ws
group = compound|simple|basic|atoms
natural = (group (","~)? )+
=> [[ flatten dup check-natural sum ]]
negative = "negative"~ ws natural => [[ -1 * ]]
zero = "zero"~ => [[ 0 ]]
integer = zero|negative|natural
 
fraction = integer "divided by"~ natural => [[ first2 / ]]
 
digit = nine|eight|seven|six|five|four|three|two|one|zero
mantissa = (ws digit ws)+
=> [[ [ number>string ] map concat ]]
decimal = integer ws "point"~ mantissa
=> [[ first2 [ number>string ] dip "." glue string>number ]]
 
number = fraction|decimal|integer
]=]
 
 
: names-to-numbers-demo ( -- )
{
"zero"
"one"
"negative one"
"nine"
"ten"
"negative seventeen"
"twenty-seven"
"one hundred"
"one hundred and one"
"negative one hundred and nineteen"
"four hundred and ninety-five thousand, three hundred and thirty-three"
"two hundred million"
"two hundred million and twenty-two"
"two hundred million, two thousand and two"
"one trillion, one billion, one million, one thousand and one"
"four hundred and fifty-three vigintillion"
"zero point one"
"one point one"
"negative one thousand, three hundred point zero zero five six seven"
"thirty-seven divided by ninety-one"
"zero divided by two nonillion"
"negative one divided by two nonillion"
}
[ dup text>number "%s => %u\n" printf ] each ;
 
names-to-numbers-demo</syntaxhighlight>
{{out}}
<pre>
zero => 0
one => 1
negative one => -1
nine => 9
ten => 10
negative seventeen => -17
twenty-seven => 27
one hundred => 100
one hundred and one => 101
negative one hundred and nineteen => -119
four hundred and ninety-five thousand, three hundred and thirty-three => 495333
two hundred million => 200000000
two hundred million and twenty-two => 200000022
two hundred million, two thousand and two => 200002002
one trillion, one billion, one million, one thousand and one => 1001001001001
four hundred and fifty-three vigintillion => 453000000000000000000000000000000000000000000000000000000000000000
zero point one => 0.1
one point one => 1.1
negative one thousand, three hundred point zero zero five six seven => -1300.00567
thirty-seven divided by ninety-one => 37/91
zero divided by two nonillion => 0
negative one divided by two nonillion => -1/2000000000000000000000000000000
</pre>
 
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 473 ⟶ 908:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 496 ⟶ 931:
=={{header|Haskell}}==
{{trans|Common Lisp}}
<langsyntaxhighlight Haskelllang="haskell">import Data.Char (toLower)
 
type Symbol = (String, Integer)
Line 617 ⟶ 1,052:
("zero":[]) -> 0
("negative":wx') -> negate $ parse illions wx'
wx' -> parse illions wx'</langsyntaxhighlight>
 
=={{header|J}}==
Define the verb usinv to convert number names to numbers.
File number_names.ijs contains the code of [[Number_names#J|number names project]].
<syntaxhighlight lang="j">
<lang J>
NB. standard profile defines tolower and delete extra blanks.
load'number_names.ijs'
 
NB. replace J's stdlib 'cut' with a variant which supports multi-character delimiters
cut =: #@:[ }.&.> [ (E. <;.1 ]) ,
 
Line 639 ⟶ 1,075:
M +/ .*+/"1 ,"2 (([: (* 100 ^ 2 ~: #) (#EN100)|EN100&i.)&>)D
)
</syntaxhighlight>
</lang>
<pre>
(-: [&.(us :.usinv))0
Line 647 ⟶ 1,083:
(-: [&.:(us :.usinv))2340202340220204x
1
</pre>
 
=={{header|jq}}==
{{trans|Wren}}
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
<syntaxhighlight lang="jq">def check(cond; msg):
if cond then . else msg | error end;
 
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
 
def trim: sub("^ +";"") | sub(" +$";"");
 
def when(cond; action):
if cond then action else . end;
 
def names: {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
"ten": 10,
"eleven": 11,
"twelve": 12,
"thirteen": 13,
"fourteen": 14,
"fifteen": 15,
"sixteen": 16,
"seventeen": 17,
"eighteen": 18,
"nineteen": 19,
"twenty": 20,
"thirty": 30,
"forty": 40,
"fifty": 50,
"sixty": 60,
"seventy": 70,
"eighty": 80,
"ninety": 90,
"hundred": 100,
"thousand": 1e3,
"million": 1e6,
"billion": 1e9,
"trillion": 1e12,
"quadrillion": 1e15
};
def zeros: ["zero", "nought", "nil", "none", "nothing"];
def nameToNum:
def seps: ",|-| and | ";
. as $name
| { text: ($name|trim|ascii_downcase) }
| (.text|startswith("minus ")) as $isNegative
| when($isNegative; .text |= (.[6:] | trim)
| when(.text|startswith("a ")); .text = "one" + .text[1:])
| [.text|splits(seps) | select(.!="")] as $words
| ($words|length) as $size
| if $size == 1 and any( zeros[]; . == $words[0]) then .sum = 0
else . + {multiplier: 1, lastNum: 0, sum: 0 }
| reduce range($size-1;-1;-1) as $i (.;
names[$words[$i]] as $num
| check($num; "'\($words[$i])' is not a valid number")
| check($num != .lastNum; "'\($name)' is not a well formed numeric string")
| if ($num >= 1000)
then check(.lastNum < 100; "'\($name)' is not a well formed numeric string")
| .multiplier = $num
| when($i == 0; .sum += .multiplier)
elif $num >= 100
then .multiplier *= 100
| when($i == 0; .sum += .multiplier)
elif $num >= 20
then check(.lastNum < 10 or .lastNum < 90;
"'\($name)' is not a well formed numeric string")
| .sum += $num * .multiplier
else check(.lastNum < 1 or .lastNum > 90;
"'\($name)' is not a well formed numeric string")
| .sum += $num * .multiplier
end
| .lastNum = $num )
end
| if $isNegative then - .sum else .sum end
;
 
def tests: [
"none",
"one",
"twenty-five",
"minus one hundred and seventeen",
"hundred and fifty-six",
"minus two thousand two",
"nine thousand, seven hundred, one",
"minus six hundred and twenty six thousand, eight hundred and fourteen",
"four million, seven hundred thousand, three hundred and eighty-six",
"fifty-one billion, two hundred and fifty-two million, seventeen thousand, one hundred eighty-four",
"two hundred and one billion, twenty-one million, two thousand and one",
"minus three hundred trillion, nine million, four hundred and one thousand and thirty-one",
"one quadrillion and one",
"minus nine quadrillion, one hundred thirty-seven"
];
 
tests[]
| "\(nameToNum|lpad(17)) = \(.)"</syntaxhighlight>
{{out}}
Exactly as for [[#Wren|Wren]].
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">const stext = ["one", "two", "three", "four", "five",
"six", "seven", "eight", "nine"]
const teentext = ["eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen",
"eighteen", "nineteen"]
const tenstext = ["ten", "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety"]
const ordstext = ["million", "billion", "trillion",
"quadrillion", "quintillion", "sextillion",
"septillion", "octillion", "nonillion",
"decillion", "undecillion", "duodecillion",
"tredecillion", "quattuordecillion", "quindecillion",
"sexdecillion", "septendecillion", "octodecillion",
"novemdecillion", "vigintillion"]
 
allnumeric = vcat(
stext, teentext, tenstext, ordstext, ["minus", "and", "hundred", "thousand", "zero"]
)
canon(word) = replace(lowercase(word), r"\-|\,|\.|\:" => "")
isnumeric(word) = canon(word) in allnumeric
 
function parsenumericphrases(txt)
words = split(strip(txt), r"(\s+)|(\s*\-\s*)")
phrases, num, alph = Vector{Pair{Bool, Vector{String}}}(), false, false
for (i, word) in enumerate(words)
if isnumeric(word) && (num || word != "and")
if !num
push!(phrases, Pair(true, String[]))
num, alph = true, false
end
if word != "and"
push!(phrases[end][2], canon(word))
end
else
if !alph
push!(phrases, Pair(false, String[]))
num, alph = false, true
if length(phrases) > 1 && !occursin(r"\w", words[i - 1][end:end])
word = words[i - 1][end] * " " * word
end
end
push!(phrases[end][2], word)
end
end
return phrases
end
 
function sumones(word, total)
n = something(findfirst(x -> x == word, stext), 0)
x = something(findfirst(x -> x == word, teentext), 0)
(x > 0) && (n += (10 + x))
n += something(findfirst(x -> x == word, tenstext), 0) * 10
return n + total
end
 
sumhundreds(word, total) = word == "hundred" ? total *= 100 : total
 
function summils(word, miltotal, onestotal)
if word == "thousand"
return miltotal + onestotal * 1000, 0
elseif (x = something(findfirst(x -> x == word, ordstext), 0)) > 0
return miltotal + onestotal * 1000^(x + 1), 0
else
return miltotal, onestotal
end
end
 
function texttointeger(txt)
phrasepairs, outputphrases = parsenumericphrases(txt), String[]
for phrase in phrasepairs
if phrase[1] # numeric phrase
wordarray, sign, onestotal, miltotal = phrase[2], 1, 0, 0
for word in wordarray
onestotal = sumones(word, onestotal)
onestotal = sumhundreds(word, onestotal)
miltotal, onestotal = summils(word, miltotal, onestotal)
end
push!(outputphrases, string(sign * (onestotal + miltotal)))
else # non-numeric phrase
push!(outputphrases, join(phrase[2], " "))
end
end
return replace(join(outputphrases, " "), r"([\w\d])\s(\,|\:|\;|\.)" => s"\1\2")
end
const examples = """
One Hundred and One Dalmatians
Two Thousand and One: A Space Odyssey
Four Score And Seven Years Ago
twelve dozen is one hundred forty-four, aka one gross
two hundred pairs of socks
Always give one hundred and ten percent effort
Change due: zero dollars and thirty-seven cents
One hour, fifty-nine minutes, forty point two seconds
Two Thousand Nineteen
Two Thousand Zero Hundred and Nineteen
Two Thousand Ten Nine
one thousand one
ninety nine thousand nine hundred ninety nine
five hundred and twelve thousand, six hundred and nine
two billion, one hundred
One Thousand One Hundred Eleven
Eleven Hundred Eleven
one hundred eleven billion one hundred eleven
Eight Thousand Eight Hundred Eighty-Eight
Eighty-Eight Hundred Eighty-Eight
one quadrillion, two trillion, three billion, four million, five thousand six
"""
 
for txt in split(strip(examples), r"\n")
println(txt, " => ", texttointeger(txt))
end
</syntaxhighlight>{{out}}
<pre>
One Hundred and One Dalmatians => 101 Dalmatians
Two Thousand and One: A Space Odyssey => 2001: A Space Odyssey
Four Score And Seven Years Ago => 4 Score 7 Years Ago
twelve dozen is one hundred forty-four, aka one gross => 12 dozen is 144, aka 1 gross
two hundred pairs of socks => 200 pairs of socks
Always give one hundred and ten percent effort => Always give 110 percent effort
Change due: zero dollars and thirty-seven cents => Change due: 0 dollars and 37 cents
One hour, fifty-nine minutes, forty point two seconds => 1 hour, 59 minutes, 40 point 2 seconds
Two Thousand Nineteen => 2019
Two Thousand Zero Hundred and Nineteen => 2019
Two Thousand Ten Nine => 2019
one thousand one => 1001
ninety nine thousand nine hundred ninety nine => 99999
five hundred and twelve thousand, six hundred and nine => 512609
two billion, one hundred => 2000000100
One Thousand One Hundred Eleven => 1111
Eleven Hundred Eleven => 1111
one hundred eleven billion one hundred eleven => 111000000111
Eight Thousand Eight Hundred Eighty-Eight => 8888
Eighty-Eight Hundred Eighty-Eight => 8888
one quadrillion, two trillion, three billion, four million, five thousand six => 1002003004005006
</pre>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
val names = mapOf<String, Long>(
Line 757 ⟶ 1,441:
)
for (name in names) println("${"%20d".format(nameToNum(name))} = $name")
}</langsyntaxhighlight>
 
{{out}}
Line 777 ⟶ 1,461:
-9223372036854775808 = minus nine quintillion, two hundred and twenty-three quadrillion, three hundred and seventy-two trillion, thirty-six billion, eight hundred and fifty-four million, seven hundred and seventy-five thousand, eight hundred and eight
</pre>
 
=={{header|Nim}}==
{{trans|Kotlin}}
<syntaxhighlight lang="nim">import re, sequtils, strformat, strutils, tables
 
const Names = {"one": 1u64,
"two": 2u64,
"three": 3u64,
"four": 4u64,
"five": 5u64,
"six": 6u64,
"seven": 7u64,
"eight": 8u64,
"nine": 9u64,
"ten": 10u64,
"eleven": 11u64,
"twelve": 12u64,
"thirteen": 13u64,
"fourteen": 14u64,
"fifteen": 15u64,
"sixteen": 16u64,
"seventeen": 17u64,
"eighteen": 18u64,
"nineteen": 19u64,
"twenty": 20u64,
"thirty": 30u64,
"forty": 40u64,
"fifty": 50u64,
"sixty": 60u64,
"seventy": 70u64,
"eighty": 80u64,
"ninety": 90u64,
"hundred": 100u64,
"thousand": 1000u64,
"million": 1000000u64,
"billion": 1000000000u64,
"trillion": 1000000000000u64,
"quadrillion": 1000000000000000u64,
"quintillion": 1000000000000000000u64}.toTable
 
let Seps = re",|-| and | "
const Zeros = ["zero", "nought", "nil", "none", "nothing"]
 
template emitError(msg: string) = raise newException(ValueError, msg)
 
 
proc nameToNum(name: string): int64 =
 
var text = name.strip().toLowerAscii
let isNegative = text.startsWith("minus ")
if isNegative: text.delete(0, 5)
if text.startsWith("a"):
text = "one" & text[1..^1]
let words = text.split(Seps).filterIt(it.len != 0)
if words.len == 1 and words[0] in Zeros:
return 0
 
var
multiplier = 1u64
lastNum, sum = 0u64
for i in countdown(words.high, 0):
let num = Names.getOrDefault(words[i], 0)
if num == 0:
emitError(&"'{words[i]}' is not a valid number")
elif num == lastNum:
emitError(&"'{name}' is not a well formed numeric string")
elif num >= 1000:
if lastNum >= 100:
emitError(&"'{name}' is not a well formed numeric string")
multiplier = num
if i == 0: sum += multiplier
elif num >= 100:
multiplier *= 100
if i == 0: sum += multiplier
elif num >= 20:
if lastNum in 10u64..90u64:
emitError(&"'{name}' is not a well formed numeric string")
sum += num * multiplier
else:
if lastNum in 1u64..90u64:
emitError(&"'{name}' is not a well formed numeric string")
sum += num * multiplier
lastNum = num
 
if isNegative and sum == uint64(int64.high) + 1:
return int64.low
if sum > uint64(int64.high):
emitError(&"'$name' is outside the range of a 64 bits integer")
 
result = if isNegative: -int64(sum) else: int64(sum)
 
 
when isMainModule:
let names = [
"none",
"one",
"twenty-five",
"minus one hundred and seventeen",
"hundred and fifty-six",
"minus two thousand two",
"nine thousand, seven hundred, one",
"minus six hundred and twenty six thousand, eight hundred and fourteen",
"four million, seven hundred thousand, three hundred and eighty-six",
"fifty-one billion, two hundred and fifty-two million, seventeen thousand, one hundred eighty-four",
"two hundred and one billion, twenty-one million, two thousand and one",
"minus three hundred trillion, nine million, four hundred and one thousand and thirty-one",
"seventeen quadrillion, one hundred thirty-seven",
"a quintillion, eight trillion and five",
"minus nine quintillion, two hundred and twenty-three quadrillion, three hundred and seventy-two trillion, thirty-six billion, eight hundred and fifty-four million, seven hundred and seventy-five thousand, eight hundred and eight"]
 
for name in names:
echo ($nametoNum(name)).align(20), " = ", name</syntaxhighlight>
 
{{out}}
<pre> 0 = none
1 = one
25 = twenty-five
-117 = minus one hundred and seventeen
156 = hundred and fifty-six
-2002 = minus two thousand two
9701 = nine thousand, seven hundred, one
-626814 = minus six hundred and twenty six thousand, eight hundred and fourteen
4700386 = four million, seven hundred thousand, three hundred and eighty-six
51252017184 = fifty-one billion, two hundred and fifty-two million, seventeen thousand, one hundred eighty-four
201021002001 = two hundred and one billion, twenty-one million, two thousand and one
-300000009401031 = minus three hundred trillion, nine million, four hundred and one thousand and thirty-one
17000000000000137 = seventeen quadrillion, one hundred thirty-seven
1000008000000000005 = a quintillion, eight trillion and five
-9223372036854775808 = minus nine quintillion, two hundred and twenty-three quadrillion, three hundred and seventy-two trillion, thirty-six billion, eight hundred and fifty-four million, seven hundred and seventy-five thousand, eight hundred and eight</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
use utf8;
binmode STDOUT, ':utf8';
 
my $phrases_with_numbers = <<'END';
Line 893 ⟶ 1,708:
 
say $_ . ' --> ' . numify($_) for grep { $_ } split "\n", $phrases_with_numbers;
say $_ . ' --> ' . comma numify($_) for grep { $_ } split "\n", $pure_numbers;</langsyntaxhighlight>
<pre>One Hundred and One Dalmatians --> 101 dalmatians
Two Thousand and One: A Space Odyssey --> 2001 : a space odyssey
Line 917 ⟶ 1,732:
Eighty-Eight Hundred Eighty-Eight --> 8888
one quadrillion, two trillion, three billion, four million, five thousand six --> 1,002,003,004,005,006</pre>
 
=={{header|Perl 6}}==
{{broken|Perl 6}}
<lang perl6>my $DEBUG = False;
 
constant @M = ('ones', 'thousand',
((<m b tr quadr quint sext sept oct non>,
(map { ('', <un duo tre quattuor quin sex septen octo novem>).flat X~ $_ },
<dec vigint trigint quadragint quinquagint sexagint septuagint octogint nonagint>),
'cent').flat X~ 'illion')).flat;
 
constant %M = @M Z=> (1, 1000, 1000000 ... *);
 
grammar Number-Names {
token TOP { ^ [.*? <number>]* .* $ }
 
method returns {
say callframe(1).subname, ' -> ', self.ast if $DEBUG;
self;
}
method trimspace {
my $pos = self.pos;
--$pos while $pos and self.orig.substr($pos-1,1) ~~ /\s/;
self.cursor($pos);
}
 
token gotsome($oldself) {
<?{ self.pos != $oldself.pos }>
}
 
token number { :i «
:my $*SOFAR = 0;
[
| 'zero' { make 0 }
| ('minus' \s+ | 'negative' \s+)?
<group>+ % [','\s+|'and'\s+|<?after \s>] <quantnoun>
{ make [+]($<group>[]».ast) * ($0 ?? -1 !! 1) * $<quantnoun>.ast }
]
<.gotsome(self)>
<.trimspace>
<.returns>
}
 
token group { :i
<?{ $*SOFAR %% 1000 }>
<hundreds> \s* <tweens($*SOFAR + $<hundreds>.ast)> \s* <zillions>
<.gotsome(self)>
\s*[ $ || <?after \W> || <?before \W> || <?before < th st nd rd th > » > ]
{
my $group = $<zillions>.ast * ($<hundreds>.ast + $<tweens>.ast);
return () if $*SOFAR and $group > $*SOFAR;
$*SOFAR += $group;
make $group;
}
<.returns>
}
 
token hundreds { :i
[
| <date> <!!{ !$*SOFAR }> { make $<date>.ast }
| <ones> ['-'|\s*] 'hundred' { make $<ones>.ast * 100 }
| <?{ not $*SOFAR }>
<tweeny>['-'|\s*] 'hundred' { make $<tweeny>.ast * 100 }
| '' { make 0 }
]
<.returns>
}
 
token tweens($c = 0) { :i
:my $*SOFAR = $c;
\s*
[
| 'ten' { make 10 }
| <teens> <!before \s*'hundred'> { make $<teens>.ast }
| <ones> \s+ 'and' \s+ <tens> { make $<ones>.ast + $<tens>.ast }
| <scores> \s+ 'and' \s+ <ones> { make $<scores>.ast + $<ones>.ast }
| <scores> \s+ 'and' \s+ <tweeny> { make $<scores>.ast + $<tweeny>.ast }
| <tens>[['-'|\s*['and'\s*]?]<ones>]? { make $<tens>.ast + ($<ones> ?? $<ones>.ast !! 0) }
| <ones> { make $<ones>.ast }
| <scores> { make $<scores>.ast }
| 'and'\s+ <?{ $c }> <tweens> { make $<tweens>.ast }
| (\d+[\.\d+]?) <?{ !$c }> { make +$0 }
| '' { make 0 }
]
\s*
<.returns>
}
 
token tweeny {
[
| <ones>[\s+|\-] { make $<ones>.ast }
| 'ten'[\s+|\-] { make 10 }
| <teens>[\s+|\-] { make $<teens>.ast }
| <tens>[[\s*|\-]<ones>]?[\s+|\-] { make $<tens>.ast + ($<ones> ?? $<ones>.ast !! 0) }
]
}
 
token date { :i
<tweeny>
[
| 'ten' { make $<tweeny>.ast * 100 + 10 }
| <teens> <!before \s*'hundred'> { make $<tweeny>.ast * 100 + $<teens>.ast }
| <tens>[['-'|\s*]<ones>]? { make $<tweeny>.ast * 100 + $<tens>.ast + ($<ones> ?? $<ones>.ast !! 0) }
| ['ought'|oh?][\s+|\-]<ones> { make $<tweeny>.ast * 100 + $<ones>.ast }
]
}
 
token scores { :i
[
| ['one'|'a']?['-'|\s*] 'score' { make 20 }
| 'two' ['-'|\s*] 'score' { make 40 }
| 'three' ['-'|\s*] 'score' { make 60 }
| 'four' ['-'|\s*] 'score' { make 80 }
]
<.returns>
}
 
token teens { :i
[
| 'eleven' { make 11 }
| 'twelve' { make 12 }
| 'twelf' { make 12 }
| 'thirteen' { make 13 }
| 'fourteen' { make 14 }
| 'fifteen' { make 15 }
| 'sixteen' { make 16 }
| 'seventeen' { make 17 }
| 'eighteen' { make 18 }
| 'nineteen' { make 19 }
]
<.returns>
}
 
token tens { :i
[
| 'twent'[y|ie] { make 20 }
| 'thirt'[y|ie] { make 30 }
| 'fort'[y|ie] { make 40 }
| 'fift'[y|ie] { make 50 }
| 'sixt'[y|ie] { make 60 }
| 'sevent'[y|ie] { make 70 }
| 'eight'[y|ie] { make 80 }
| 'ninet'[y|ie] { make 90 }
]
<.returns>
}
 
token ones { :i
[
| 'one' { make 1 }
| 'fir'<?before st> { make 1 }
| 'two' { make 2 }
| 'seco'<?before nd> { make 2 }
| 'three' { make 3 }
| 'thi'<?before rd> { make 3 }
| 'four' { make 4 }
| 'five' { make 5 }
| 'fif'<?before th> { make 5 }
| 'six' { make 6 }
| 'seven' { make 7 }
| 'eight' { make 8 }
| 'eigh'<?before th> { make 8 }
| 'nine' { make 9 }
| 'nin'<?before th> { make 9 }
| <?{ !$*SOFAR }> ['a'\s+]? <?before 'hundred' | 'thousand' | <zillions> <?{ $<zillions>.Str ne '' }> > { make 1 }
]
<.returns>
}
 
token zillions { :i
[
| (\w+) <?{ %M{lc ~$0} }> { make +%M{lc ~$0} }
| <quantnoun> { make $<quantnoun>.ast }
| '' { make 1 }
]
<.returns>
}
 
token quantnoun { :i
\s*
[
| 'pair's? ' of'? { make 2 }
| 'dozen' { make 12 }
| 'gross' ' of'? { make 144 }
| '' { make 1 }
]
<.returns>
}
}
 
sub commify($_) {
/\d\d\d\d\d/
?? .flip.subst(/\d\d\d<?before \d>/, -> $/ {$/~','},:g).flip
!! $_;
}
 
sub MAIN ($file = 'numnames') {
$DEBUG = True if $file eq '-';
my $fh = $file eq '-' ?? $*IN !! open($file);
for $fh.lines -> $line {
say $line;
my $parse = Number-Names.parse($line);
if $parse and +$parse<number> {
print "\t==> ";
my $prev = 0;
for $parse<number>[*] -> $n {
print substr($line, $prev, $n.from - $prev);
print commify(~$n.ast);
$prev = $n.to;
}
say substr($line, $prev);
}
}
}</lang>
{{out}}
<pre>Seventy-two dollars
==> 72 dollars
Seventy two dollars
==> 72 dollars
One Hundred and One Dalmatians
==> 101 Dalmatians
A Hundred and One Dalmatians
==> 101 Dalmatians
One Hundred One Dalmatians
==> 101 Dalmatians
Hundred and One Dalmatians
==> 101 Dalmatians
One Thousand and One Nights
==> 1001 Nights
Two Thousand and One: A Space Odyssey
==> 2001: A Space Odyssey
math one-oh-one
==> math 101
Charlemagne died in eight-fourteen.
==> Charlemagne died in 814.
ten sixty-six
==> 1066
Nineteen Ought Three
==> 1903
Nineteen Eighty-Four
==> 1984
Twenty Thirteen
==> 2013
four billion, two hundred ninety-four million, nine hundred sixty-seven thousand, two hundred ninety five
==> 4,294,967,295
Nine quadrillion, seven trillion, one hundred ninety-nine billion, two hundred fifty-four million, seven hundred forty thousand, nine hundred ninety two
==> 9,007,199,254,740,992
Nine Hundred Ninety-Nine
==> 999
One Thousand One Hundred Eleven
==> 1111
Eleven Hundred Eleven
==> 1111
Eight Thousand Eight Hundred Eighty-Eight
==> 8888
Eighty-Eight Hundred Eighty-Eight
==> 8888
Seven Million Seven Hundred Seventy-Seven Thousand Seven Hundred Seventy-Seven
==> 7,777,777
Ninety-Nine Trillion Nine Hundred Ninety-Nine Billion Nine Hundred Ninety-Nine Million Nine Hundred Ninety-Nine Thousand Nine Hundred Ninety-Nine
==> 99,999,999,999,999
ninety-nine
==> 99
three hundred
==> 300
three hundred and ten
==> 310
one thousand, five hundred and one
==> 1501
twelve thousand, six hundred and nine
==> 12,609
five hundred and twelve thousand, six hundred and nine
==> 512,609
forty-three million, one hundred and twelve thousand, six hundred and nine
==> 43,112,609
two billion, one hundred
==> 2,000,000,100
zero
==> 0
eight
==> 8
one hundred
==> 100
one hundred twenty three
==> 123
one thousand one
==> 1001
ninety nine thousand nine hundred ninety nine
==> 99,999
one hundred thousand
==> 100,000
nine billion one hundred twenty three million four hundred fifty six thousand seven hundred eighty nine
==> 9,123,456,789
one hundred eleven billion one hundred eleven
==> 111,000,000,111
sing a song of sixpence, a pocket full of rye, four and twenty blackbirds baked in a pie
==> sing a song of sixpence, a pocket full of rye, 24 blackbirds baked in a pie
Fourscore and seven years ago, our four fathers...
==> 87 years ago, our 4 fathers...
The Ninety and Nine
==> The 99
Seven Brides for Seven Brothers
==> 7 Brides for 7 Brothers
Cheaper by the Dozen
==> Cheaper by the 12
five dozen roses
==> 60 roses
a dozen dozen roses
==> 144 roses
two gross of eggs
==> 288 eggs
two hundred pairs of socks
==> 400 socks
The First Noël
==> The 1st Noël
second place
==> 2nd place
Forty-second Street
==> 42nd Street
the twenty-third Psalm
==> the 23rd Psalm
The Fourth Estate
==> The 4th Estate
The Fifth Essence
==> The 5th Essence
The sixth sick shiek's sixth sheep's sick.
==> The 6th sick shiek's 6th sheep's sick.
in seventh heaven
==> in 7th heaven
The Eighth Wonder of the World!
==> The 8th Wonder of the World!
Malher's Ninth Symphony
==> Malher's 9th Symphony
a tenth of all he had
==> a 10th of all he had
the eleventh hour
==> the 11th hour
Twelfth Night
==> 12th Night
Friday the Thirteenth
==> Friday the 13th
Twentieth-Century Fox
==> 20th-Century Fox
one novemseptuagintillion, one octoseptuagintillion, one septenseptuagintillion, one sexseptuagintillion, one quinseptuagintillion, one quattuorseptuagintillion, one treseptuagintillion, one duoseptuagintillion, one unseptuagintillion, one septuagintillion, one novemsexagintillion, one octosexagintillion, one septensexagintillion, one sexsexagintillion, one quinsexagintillion, one quattuorsexagintillion, one tresexagintillion, one duosexagintillion, one unsexagintillion, one sexagintillion, one novemquinquagintillion, one octoquinquagintillion, one septenquinquagintillion, one sexquinquagintillion, one quinquinquagintillion, one quattuorquinquagintillion, one trequinquagintillion, one duoquinquagintillion, one unquinquagintillion, one quinquagintillion, one novemquadragintillion, one octoquadragintillion, one septenquadragintillion, one sexquadragintillion, one quinquadragintillion, one quattuorquadragintillion, one trequadragintillion, one duoquadragintillion, one unquadragintillion, one quadragintillion, one novemtrigintillion, one octotrigintillion, one septentrigintillion, one sextrigintillion, one quintrigintillion, one quattuortrigintillion, one tretrigintillion, one duotrigintillion, one untrigintillion, one trigintillion, one novemvigintillion, one octovigintillion, one septenvigintillion, one sexvigintillion, one quinvigintillion, one quattuorvigintillion, one trevigintillion, one duovigintillion, one unvigintillion, one vigintillion, one novemdecillion, one octodecillion, one septendecillion, one sexdecillion, one quindecillion, one quattuordecillion, one tredecillion, one duodecillion, one undecillion, one decillion, one nonillion, one octillion, one septillion, one sextillion, one quintillion, one quadrillion, one trillion, one billion, one million, one thousand, one
==> 1,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001,001</pre>
 
=={{header|Phix}}==
Uses [[Number_names#Phix|Number_names]] as an executable library.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>--
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Names_to_numbers.exw
-- demo\rosetta\Names_to_numbers.exw
--
-- ---------------------------------
include demo\rosetta\Number_names.exw
--</span>
 
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
constant {tokens,tokvals} = columnize({{"zero",0},{"one",1},{"two",2},{"three",3},{"four",4},{"five",5},{"six",6},
<span style="color: #008080;">include</span> <span style="color: #000000;">demo</span><span style="color: #0000FF;">\</span><span style="color: #000000;">rosetta</span><span style="color: #0000FF;">\</span><span style="color: #000000;">Number_names</span><span style="color: #0000FF;">.</span><span style="color: #000000;">exw</span>
{"seven",7},{"eight",8},{"nine",9},{"ten",10},
{"eleven",11},{"twelve",12},{"thirteen",13},{"fourteen",14},{"fifteen",15},
<span style="color: #008080;">constant</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">tokens</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tokvals</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">columnize</span><span style="color: #0000FF;">({{</span><span style="color: #008000;">"zero"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"one"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"two"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"three"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"four"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"five"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"six"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">},</span>
{"sixteen",16},{"seventeen",17},{"eighteen",18},{"nineteen",19},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"seven"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"eight"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"nine"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"ten"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">},</span>
{"twenty",20},{"thirty",30},{"forty",40},{"fifty",50},{"sixty",60},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"eleven"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">11</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"twelve"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">12</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"thirteen"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">13</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"fourteen"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">14</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"fifteen"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">15</span><span style="color: #0000FF;">},</span>
{"seventy",70},{"eighty",80},{"ninety",90},{"hundred",100},{"thousand",1e3},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"sixteen"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">16</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"seventeen"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">17</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"eighteen"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">18</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"nineteen"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">19</span><span style="color: #0000FF;">},</span>
{"million",1e6},{"billion",1e9},{"trillion",1e12}})
<span style="color: #0000FF;">{</span><span style="color: #008000;">"twenty"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">20</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"thirty"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">30</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"forty"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">40</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"fifty"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">50</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"sixty"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">60</span><span style="color: #0000FF;">},</span>
function parse(string s)
<span style="color: #0000FF;">{</span><span style="color: #008000;">"seventy"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">70</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"eighty"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">80</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"ninety"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">90</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"hundred"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">100</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"thousand"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1e3</span><span style="color: #0000FF;">},</span>
sequence words
<span style="color: #0000FF;">{</span><span style="color: #008000;">"million"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1e6</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"billion"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1e9</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"trillion"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1e12</span><span style="color: #0000FF;">}})</span>
integer negmul = 1, hund = 0
atom total = 0, k
<span style="color: #008080;">function</span> <span style="color: #000000;">parse</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
s = substitute(s,",","")
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">substitute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008000;">","</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">)</span>
s = substitute(s," and "," ")
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">substitute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" and "</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">)</span>
s = substitute(s,"-"," ")
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">substitute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"-"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">)</span>
words = split(s)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">words</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
if length(words)=0 then return "invalid" end if
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #008000;">"invalid"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if words[1]=="minus" then
<span style="color: #004080;">integer</span> <span style="color: #000000;">negmul</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hund</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
negmul = -1
<span style="color: #008080;">if</span> <span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]==</span><span style="color: #008000;">"minus"</span> <span style="color: #008080;">then</span>
words = words[2..$]
<span style="color: #000000;">negmul</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
end if
<span style="color: #000000;">words</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..$]</span>
for i=1 to length(words) do
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
k = find(words[i],tokens)
<span style="color: #004080;">atom</span> <span style="color: #000000;">total</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
if k=0 then
<span style="color: #008080;">for</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: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
if words[i]!="point" then return "invalid" end if
<span style="color: #004080;">atom</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">tokens</span><span style="color: #0000FF;">)</span>
total += hund
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
hund = 0
<span style="color: #008080;">if</span> <span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]!=</span><span style="color: #008000;">"point"</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #008000;">"invalid"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
integer tens = 10
<span style="color: #000000;">total</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">hund</span>
for j=i+1 to length(words) do
<span style="color: #000000;">hund</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
k = find(words[j],tokens)
<span style="color: #004080;">integer</span> <span style="color: #000000;">tens</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">10</span>
if k=0 then return "invalid" end if
<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: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
k = tokvals[k]
<span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span><span style="color: #000000;">tokens</span><span style="color: #0000FF;">)</span>
if k>9 then return "invalid" end if
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #008000;">"invalid"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
total += k/tens
<span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">tokvals</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span>
tens *= 10
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">></span><span style="color: #000000;">9</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #008000;">"invalid"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #000000;">total</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">/</span><span style="color: #000000;">tens</span>
exit
<span style="color: #000000;">tens</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">10</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
k = tokvals[k]
<span style="color: #008080;">exit</span>
if k<100 then
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
hund += k
<span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">tokvals</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span>
elsif k=100 then
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span><span style="color: #0000FF;"><</span><span style="color: #000000;">100</span> <span style="color: #008080;">then</span>
hund *= k
<span style="color: #000000;">hund</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">k</span>
else
<span style="color: #008080;">elsif</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">100</span> <span style="color: #008080;">then</span>
total += hund*k
<span style="color: #000000;">hund</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">k</span>
hund = 0
<span style="color: #008080;">else</span>
end if
<span style="color: #000000;">total</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">hund</span><span style="color: #0000FF;">*</span><span style="color: #000000;">k</span>
end for
<span style="color: #000000;">hund</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
return negmul*(total+hund)
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
 
<span style="color: #008080;">return</span> <span style="color: #000000;">negmul</span><span style="color: #0000FF;">*(</span><span style="color: #000000;">total</span><span style="color: #0000FF;">+</span><span style="color: #000000;">hund</span><span style="color: #0000FF;">)</span>
atom si
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
for i=1 to length(Samples) do
si = Samples[i]
<span style="color: #008080;">for</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: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">samples</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
string s = spell(si)
<span style="color: #004080;">atom</span> <span style="color: #000000;">si</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">samples</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
-- if parse(s)=si then
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">spell</span><span style="color: #0000FF;">(</span><span style="color: #000000;">si</span><span style="color: #0000FF;">)</span>
if abs(parse(s)-si)<1e-6 then
<span style="color: #008080;">if</span> <span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">parse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">si</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">1e-6</span> <span style="color: #008080;">then</span>
s = "<==> "&s
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"&lt;==&gt; "</span><span style="color: #0000FF;">&</span><span style="color: #000000;">s</span>
else
<span style="color: #008080;">else</span>
s = "???? "&s
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"???? "</span><span style="color: #0000FF;">&</span><span style="color: #000000;">s</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
printf(1,"%18s %s\n",{smartp(si),s})
<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;">"%18s %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">smartp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">si</span><span style="color: #0000FF;">),</span><span style="color: #000000;">s</span><span style="color: #0000FF;">})</span>
end for</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre style="font-size: 8px">
Line 1,378 ⟶ 1,851:
 
<small>Note: This example and [[Number_names#Python]] need to be kept in sync</small>
<langsyntaxhighlight lang="python">from spell_integer import spell_integer, SMALL, TENS, HUGE
 
def int_from_words(num):
Line 1,430 ⟶ 1,903:
num = int_from_words(txt)
print('%12i <%s> %s' % (n, '==' if n == num else '??', txt))
print('')</langsyntaxhighlight>
{{out}}
<pre>##
Line 1,460 ⟶ 1,933:
-2 <==> minus two
0 <==> zero</pre>
 
=={{header|Quackery}}==
 
The idea is that, with a few tweaks and appropriate definitions for number names etc, a string such as <pre>one billion, two hundred and thirty four million, five hundred and sixty seven thousand, eight hundred and ninety</pre> can ''be'' a valid Quackery program.
 
The tweaks turn it into the nest <pre>[ {{ one billion , two hundred thirty four million , five hundred sixty seven thousand , eight hundred ninety }} ]</pre> by prepending <code>{{ </code>, inserting a space in front of each comma, and appending <code> }}</code> before being compiled with <code>build</code>, and removing references to the word <code>and</code> after compilation.
 
 
Finally, the compiled nest is executed with <code>do</code>.
 
<syntaxhighlight lang="quackery"> [ 1 + ] is one ( --> n )
[ 2 + ] is two ( --> n )
[ 3 + ] is three ( --> n )
[ 4 + ] is four ( --> n )
[ 5 + ] is five ( --> n )
[ 6 + ] is six ( --> n )
[ 7 + ] is seven ( --> n )
[ 8 + ] is eight ( --> n )
[ 9 + ] is nine ( --> n )
[ 10 + ] is ten ( --> n )
[ 11 + ] is eleven ( --> n )
[ 12 + ] is twelve ( --> n )
[ 13 + ] is thirteen ( --> n )
[ 14 + ] is fourteen ( --> n )
[ 15 + ] is fifteen ( --> n )
[ 16 + ] is sixteen ( --> n )
[ 17 + ] is seventeen ( --> n )
[ 18 + ] is eighteen ( --> n )
[ 19 + ] is nineteen ( --> n )
[ 20 + ] is twenty ( --> n )
[ 30 + ] is thirty ( --> n )
[ 40 + ] is forty ( --> n )
[ 50 + ] is fifty ( --> n )
[ 60 + ] is sixty ( --> n )
[ 70 + ] is seventy ( --> n )
[ 80 + ] is eighty ( --> n )
[ 90 + ] is ninety ( --> n )
 
[ 100 * ] is hundred ( n --> n )
[ 1000 * ] is thousand ( n --> n )
[ thousand thousand ] is million ( n --> n )
[ thousand million ] is billion ( n --> n )
 
[ 0 0 ] is {{ ( --> n n )
[ + 0 ] is , ( n n --> n n )
[ + ] is }} ( n n --> n )
 
[ $ "{{ " swap
witheach
[ dup char , = if
[ dip space join ]
join ]
$ " }}" join
build
[]
swap witheach
[ dup ' and = iff
drop
else
[ nested join ] ]
do ] is name->number ( $ --> n )
 
$ "one billion, two hundred and thirty four million, five hundred and sixty seven thousand, eight hundred and ninety"
name->number echo</syntaxhighlight>
 
{{out}}
 
<pre>1234567890</pre>
 
=={{header|Racket}}==
Line 1,465 ⟶ 2,006:
Extension of the [[Number_names#Racket | number to names]] code:
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 1,530 ⟶ 2,071:
(printf "~s <-> ~a\n" n eng)
(printf "Fail: ~s -> ~a -> ~s\n" n eng n2)))
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,545 ⟶ 2,086:
552966175718680570 <-> five hundred and fifty-two quadrillion, nine hundred and sixty-six trillion, one hundred and seventy-five billion, seven hundred and eighteen million, six hundred and eighty thousand, five hundred and seventy
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{trans|Perl}}
<syntaxhighlight lang="raku" line>my $phrases-with-numbers = q:to/END/;
One Hundred and One Dalmatians
Two Thousand and One: A Space Odyssey
 
Four Score And Seven Years Ago
twelve dozen is one hundred forty-four, aka one gross
two hundred pairs of socks
Always give one hundred and ten percent effort
Change due: zero dollars and thirty-seven cents
 
One hour, fifty-nine minutes, forty point two seconds
π ≅ three point one four one five nine
END
 
my $pure-numbers = q:to/END/;
Twenty Nineteen
Two Thousand Nineteen
Two Thousand Zero Hundred and Nineteen
Two Thousand Ten Nine
 
one thousand one
ninety nine thousand nine hundred ninety nine
five hundred and twelve thousand, six hundred and nine
two billion, one hundred
 
One Thousand One Hundred Eleven
Eleven Hundred Eleven
one hundred eleven billion one hundred eleven
Eight Thousand Eight Hundred Eighty-Eight
Eighty-Eight Hundred Eighty-Eight
 
Forty-two quintillion, one quadrillion, two trillion, three billion, four million, five thousand six
END
 
my %nums = (
zero => 0, one => 1, two => 2, three => 3,
four => 4, five => 5, six => 6, seven => 7,
eight => 8, nine => 9, ten => 10, eleven => 11,
twelve => 12, thirteen => 13, fourteen => 14, fifteen => 15,
sixteen => 16, seventeen => 17, eighteen => 18, nineteen => 19,
twenty => 20, thirty => 30, forty => 40, fifty => 50,
sixty => 60, seventy => 70, eighty => 80, ninety => 90,
hundred => 100, thousand => 1_000, million => 1_000_000,
billion => 1_000_000_000, trillion => 1_000_000_000_000,
quadrillion => 1_000_000_000_000_000, quintillion => 1_000_000_000_000_000_000
);
 
# groupings: thousand million billion trillion quadrillion quintillion
my token groups { \d**4 | \d**7 | \d**10 | \d**13 | \d**16 | \d**19 };
 
# remove hyphens/spaces: leading, trailing, multiple
sub squeeze ($str is copy) { $str ~~ s:g/'-' | \s+ / /; $str .=trim }
 
# commify larger numbers for readabilty
sub comma { $^i.chars > 4 ?? $^i.flip.comb(3).join(',').flip !! $^i }
 
sub numify ($str is copy) {
$str = squeeze $str.lc;
$str ~~ s:g/(.)(<punct>)/$0 $1/;
 
for %nums.kv -> $word, $number { $str ~~ s:g/ <|w> $word <|w> / $number / }
 
$str ~~ s:g/(\d+)<ws> <?before \d>/$0/ if $str ~~ /(point )<ws>[(\d)<ws>]+$/;
$str ~~ s:g/(\d+) <ws> 'score' / {$0 * 20} /;
$str ~~ s:g/(\d) <ws> [','|'and'] <ws> (\d)/$0 $1/;
 
$str ~~ s:g/ <|w> (\d) <ws> 100 <ws> (\d\d) <ws> (\d) <ws> (<groups>) <|w> / {($0 * 100 + $1 + $2) * $3} /;
$str ~~ s:g/ <|w> (\d) <ws> 100 <ws> (\d ** 1..2) <ws> (<groups>) <|w> / {($0 * 100 + $1) * $2} /;
$str ~~ s:g/ <|w> (\d) <ws> 100 <ws> (<groups>) <|w> / { $0 * 100 * $1} /;
$str ~~ s:g/ <|w> <ws> 100 <ws> (\d\d) <ws> (\d) <ws> (<groups>) <|w> / {($0 + 100 + $1) * $2} /;
$str ~~ s:g/ <|w> <ws> 100 <ws> (\d ** 1..2) <ws> (<groups>) <|w> / {($0 + 100 ) * $1} /;
$str ~~ s:g/ <|w> <ws> 100 <ws> (<groups>) <|w> / { $0 * 100} /;
$str ~~ s:g/ <|w> (\d\d) <ws> (\d) <ws> (<groups>) <|w> / {($0 + $1) * $2} /;
$str ~~ s:g/ <|w> (\d ** 1..2) <ws> (<groups>) <|w> / { $0 * $1} /;
$str ~~ s:g/ <|w> (\d\d) <ws> (\d) <ws> 100 <|w> / {($0 + $1) * 100} /;
$str ~~ s:g/ <|w> (\d ** 1..2) <ws> 100 <|w> / { $0 * 100} /;
$str ~~ s:g/ <|w> (\d ** 2)<ws>(\d ** 2) <|w> / { $0 * 100 + $1} /;
 
$str ~~ s:g/( [\d+<ws>]* \d+ ) / {[+] $0.split: ' '} /;
 
$str ~~ s:g/(\d+) <ws> 'pairs of' / {$0 * 2} /;
$str ~~ s:g/(\d+) <ws> 'dozen' / {$0 * 12} /;
$str ~~ s:g/(\d+) <ws> 'point' <ws> (\d+) / $0.$1 /;
$str ~~ s:g/(\d+) <ws> 'percent' / $0% /;
$str ~~ s:g/(\d+) <ws> 'dollars' / \$$0 /;
$str ~~ s:g/(\d+) <ws> 'cents' / $0¢ /;
 
squeeze $str;
}
 
say $_ ~ ' --> ' ~ .&numify for $phrases-with-numbers.split("\n").grep: *.so;
say $_ ~ ' --> ' ~ .&numify.&comma for $pure-numbers.split("\n").grep: *.so;</syntaxhighlight>
{{out}}
<pre>One Hundred and One Dalmatians --> 101 dalmatians
Two Thousand and One: A Space Odyssey --> 2001 : a space odyssey
Four Score And Seven Years Ago --> 87 years ago
twelve dozen is one hundred forty-four, aka one gross --> 144 is 144 , aka 1 gross
two hundred pairs of socks --> 400 socks
Always give one hundred and ten percent effort --> always give 110% effort
Change due: zero dollars and thirty-seven cents --> change due : $0 and 37¢
One hour, fifty-nine minutes, forty point two seconds --> 1 hour , 59 minutes , 40.2 seconds
π ≅ three point one four one five nine --> π ≅ 3.14159
Twenty Nineteen --> 2019
Two Thousand Nineteen --> 2019
Two Thousand Zero Hundred and Nineteen --> 2019
Two Thousand Ten Nine --> 2019
one thousand one --> 1001
ninety nine thousand nine hundred ninety nine --> 99,999
five hundred and twelve thousand, six hundred and nine --> 512,609
two billion, one hundred --> 2,000,000,100
One Thousand One Hundred Eleven --> 1111
Eleven Hundred Eleven --> 1111
one hundred eleven billion one hundred eleven --> 111,000,000,111
Eight Thousand Eight Hundred Eighty-Eight --> 8888
Eighty-Eight Hundred Eighty-Eight --> 8888
Forty-two quintillion, one quadrillion, two trillion, three billion, four million, five thousand six --> 42,001,002,003,004,005,006</pre>
 
=={{header|Ruby}}==
This solution uses "Number names" from [[Number_names#Ruby | here]]
{{trans|Python}}
<langsyntaxhighlight lang="ruby">require 'number_names'
 
def int_from_words(num)
Line 1,579 ⟶ 2,240:
end
negmult * (total + small)
end</langsyntaxhighlight>
 
Examples:
<langsyntaxhighlight lang="ruby">for n in (-10000..10000).step(17)
raise unless n == int_from_words(wordify(n))
end
Line 1,605 ⟶ 2,266:
break if n==0
n /= -10
end</langsyntaxhighlight>
 
{{out}}
Line 1,640 ⟶ 2,301:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func names_to_number(str) {
 
static nums = Hash.new(
Line 1,710 ⟶ 2,371:
str.gsub!(/\b(\d{2}) (\d{2})\b/, {|a,b| (a.to_i * 100) + b.to_i});
str.gsub!(regex[10], {|a| a.split(' ').map{.to_i}.sum });
}</langsyntaxhighlight>
 
Usage:
<langsyntaxhighlight lang="ruby">ARGF.each { |line|
say "#{line.chomp.dump} --> #{names_to_number(line).dump}";
}</langsyntaxhighlight>
 
Sample:
Line 1,735 ⟶ 2,396:
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
proc name2num name {
set words [regexp -all -inline {[a-z]+} [string tolower $name]]
Line 1,786 ⟶ 2,447:
}
return [expr {$sign * [tcl::mathop::+ {*}$groups]}]
}</langsyntaxhighlight>
Demonstrating/testing (based on [[#Perl|Perl]] code's samples):
<langsyntaxhighlight lang="tcl">set samples {
"Seventy-two dollars"
"Seventy two dollars"
Line 1,829 ⟶ 2,490:
foreach s $samples {
puts "$s => [name2num $s]"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,869 ⟶ 2,530:
one hundred eleven billion one hundred eleven => 111000000111
minus fifty six => -56
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-str}}
{{libheader|Wren-pattern}}
{{libheader|Wren-fmt}}
Wren's built in Num type can only deal accurately with integers up to 16 digits long (plus or minus 2 ^ 53) so without resorting to BigInt (which would be overkill here) we can only deal with numbers up to nine quadrillion or so.
<syntaxhighlight lang="wren">import "./str" for Str
import "./pattern" for Pattern
import "./fmt" for Fmt
var names = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
"ten": 10,
"eleven": 11,
"twelve": 12,
"thirteen": 13,
"fourteen": 14,
"fifteen": 15,
"sixteen": 16,
"seventeen": 17,
"eighteen": 18,
"nineteen": 19,
"twenty": 20,
"thirty": 30,
"forty": 40,
"fifty": 50,
"sixty": 60,
"seventy": 70,
"eighty": 80,
"ninety": 90,
"hundred": 100,
"thousand": 1e3,
"million": 1e6,
"billion": 1e9,
"trillion": 1e12,
"quadrillion": 1e15
}
 
var zeros = ["zero", "nought", "nil", "none", "nothing"]
 
var seps = Pattern.new("[,|-| and | ]")
 
var nameToNum = Fn.new { |name|
var text = Str.lower(name.trim())
var isNegative = text.startsWith("minus ")
if (isNegative) text = text[6..-1]
if (text.startsWith("a ")) text = "one" + text[1..-1]
var words = seps.splitAll(text).where { |w| w != "" }.toList
var size = words.count
if (size == 1 && zeros.contains(words[0])) return 0
var multiplier = 1
var lastNum = 0
var sum = 0
for (i in size-1..0) {
var num = names[words[i]]
if (!num) Fiber.abort("'%(words[i])' is not a valid number")
if (num == lastNum) Fiber.abort("'%(name)' is not a well formed numeric string")
if (num >= 1000) {
if (lastNum >= 100) {
Fiber.abort("'%(name)' is not a well formed numeric string")
}
multiplier = num
if (i == 0) sum = sum + multiplier
} else if (num >= 100) {
multiplier = multiplier * 100
if (i == 0) sum = sum + multiplier
} else if (num >= 20) {
if (lastNum >= 10 && lastNum <= 90) {
Fiber.abort("'%(name)' is not a well formed numeric string")
}
sum = sum + num*multiplier
} else {
if (lastNum >= 1 && lastNum <= 90) {
Fiber.abort("'%(name)' is not a well formed numeric string")
}
sum = sum + num*multiplier
}
lastNum = num
}
return (isNegative) ? -sum : sum
}
 
var tests = [
"none",
"one",
"twenty-five",
"minus one hundred and seventeen",
"hundred and fifty-six",
"minus two thousand two",
"nine thousand, seven hundred, one",
"minus six hundred and twenty six thousand, eight hundred and fourteen",
"four million, seven hundred thousand, three hundred and eighty-six",
"fifty-one billion, two hundred and fifty-two million, seventeen thousand, one hundred eighty-four",
"two hundred and one billion, twenty-one million, two thousand and one",
"minus three hundred trillion, nine million, four hundred and one thousand and thirty-one",
"one quadrillion and one",
"minus nine quadrillion, one hundred thirty-seven"
]
for (name in tests) Fmt.print("$17d = $s", nameToNum.call(name), name)</syntaxhighlight>
 
{{out}}
<pre>
0 = none
1 = one
25 = twenty-five
-117 = minus one hundred and seventeen
156 = hundred and fifty-six
-2002 = minus two thousand two
9701 = nine thousand, seven hundred, one
-626814 = minus six hundred and twenty six thousand, eight hundred and fourteen
4700386 = four million, seven hundred thousand, three hundred and eighty-six
51252017184 = fifty-one billion, two hundred and fifty-two million, seventeen thousand, one hundred eighty-four
201021002001 = two hundred and one billion, twenty-one million, two thousand and one
-300000009401031 = minus three hundred trillion, nine million, four hundred and one thousand and thirty-one
1000000000000001 = one quadrillion and one
-9000000000000137 = minus nine quadrillion, one hundred thirty-seven
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">var names=T("zero","one","two","three","four","five","six","seven","eight",
"nine","ten","eleven","twelve","thirteen","fourteen","fifteen",
"sixteen","seventeen","eighteen","nineteen","twenty",
Line 1,901 ⟶ 2,687:
}
minus*(total + hund)
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">foreach s in (T("eighty-five thousand and one ",
" one hundred and fifty-five thousand and nineteen",
"one thousand, nine hundred and eighty-four","Nineteen Eighty-Four",
Line 1,911 ⟶ 2,697:
"six million, seven hundred and sixty-six thousand and twenty-seven")){
println("\"%s\" is %,d".fmt(s,stringToNumber(s)));
}</langsyntaxhighlight>
{{out}}
<pre>
9,487

edits