Names to numbers: Difference between revisions

m
m (Added the Sidef language)
m (→‎{{header|Wren}}: Minor tidy)
 
(39 intermediate revisions by 15 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}}
<syntaxhighlight lang="go">package main
 
import (
"fmt"
"math"
"regexp"
"strings"
)
 
var names = map[string]int64{
"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": 1000,
"million": 1000000,
"billion": 1000000000,
"trillion": 1000000000000,
"quadrillion": 1000000000000000,
"quintillion": 1000000000000000000,
}
 
var seps = regexp.MustCompile(`,|-| and | `)
var zeros = regexp.MustCompile(`^(zero|nought|nil|none|nothing)$`)
 
func nameToNum(name string) (int64, error) {
text := strings.ToLower(strings.TrimSpace(name))
isNegative := strings.HasPrefix(text, "minus ")
if isNegative {
text = text[6:]
}
if strings.HasPrefix(text, "a ") {
text = "one" + text[1:]
}
words := seps.Split(text, -1)
for i := len(words) - 1; i >= 0; i-- {
if words[i] == "" {
if i < len(words)-1 {
copy(words[i:], words[i+1:])
}
words = words[:len(words)-1]
}
}
size := len(words)
if size == 1 && zeros.MatchString(words[0]) {
return 0, nil
}
var multiplier, lastNum, sum int64 = 1, 0, 0
for i := size - 1; i >= 0; i-- {
num, ok := names[words[i]]
if !ok {
return 0, fmt.Errorf("'%s' is not a valid number", words[i])
} else {
switch {
case num == lastNum, num >= 1000 && lastNum >= 100:
return 0, fmt.Errorf("'%s' is not a well formed numeric string", name)
case num >= 1000:
multiplier = num
if i == 0 {
sum += multiplier
}
case num >= 100:
multiplier *= 100
if i == 0 {
sum += multiplier
}
case num >= 20 && lastNum >= 10 && lastNum <= 90:
return 0, fmt.Errorf("'%s' is not a well formed numeric string", name)
case num >= 20:
sum += num * multiplier
case lastNum >= 1 && lastNum <= 90:
return 0, fmt.Errorf("'%s' is not a well formed numeric string", name)
default:
sum += num * multiplier
}
}
lastNum = num
}
 
if isNegative && sum == -sum {
return math.MinInt64, nil
}
if sum < 0 {
return 0, fmt.Errorf("'%s' is outside the range of an int64", name)
}
if isNegative {
return -sum, nil
} else {
return sum, nil
}
}
 
func main() {
names := [...]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",
}
for _, name := range names {
num, err := nameToNum(name)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%20d = %s\n", num, 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|Haskell}}==
{{trans|Common Lisp}}
<langsyntaxhighlight Haskelllang="haskell">import Data.Char (toLower)
 
type Symbol = (String, Integer)
Line 452 ⟶ 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 474 ⟶ 1,075:
M +/ .*+/"1 ,"2 (([: (* 100 ^ 2 ~: #) (#EN100)|EN100&i.)&>)D
)
</syntaxhighlight>
</lang>
<pre>
(-: [&.(us :.usinv))0
Line 484 ⟶ 1,085:
</pre>
 
=={{header|Perljq}}==
{{trans|Wren}}
The following code reads a file line-by-line. It echos comment lines starting with a hashmark and blank lines. Remaining lines are output followed by an arrow "=>" and any non-negative integer number names translated into numbers, e.g., a line with "ninety-nine" is output like this: "ninety-nine => 99".
{{works with|jq}}
<lang perl>use strict;
'''Works with gojq, the Go implementation of jq'''
use List::Util qw(sum);
 
<syntaxhighlight lang="jq">def check(cond; msg):
our %nums = (
if cond then . else msg | error end;
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,
# My ActiveState Win32 Perl uses e-notation after 999_999_999_999_999
quadrillion => 1e+015, quintillion => 1e+018);
 
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
# Groupings for thousands, millions, ..., quintillions
our $groups = qr/\d{4}|\d{7}|\d{10}|\d{13}|1e\+015|1e\+018/;
 
def trim: sub("^ +";"") | sub(" +$";"");
# Numeral or e-notation
our $num = qr/\d+|\d+e\+\d+/;
 
def when(cond; action):
while (<>) {
if cond then action else . end;
# skip blank lines
if(/^\s*$/) { print; next; }
# echo comment lines
if( /^\s*#.*$/ ) { print; next; }
chomp;
my $orig = $_;
s/-/ /g; # convert hyphens to spaces
s/\s\s+/ /g; # remove duplicate whitespace, convert ws to space
s/ $//g; # remove trailing blank
s/^ //g; # remove leading blank
$_ = lc($_); # convert to lower case
# tokenize sentence boundaries
s/([\.\?\!]) / $1\n/g;
s/([\.\?\!])$/ $1\n/g;
# tokenize other punctuation and symbols
s/\$(.)/\$ $1/g; # prefix
s/(.)([\;\:\%',])/$1 $2/g; # suffix
 
def names: {
foreach my $key (keys %nums) { s/\b$key\b/$nums{$key}/eg; }
"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: [
s/(\d) , (\d)/$1 $2/g;
"none",
s/(\d) and (\d)/$1 $2/g;
"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[]
s/\b(\d) 100 (\d\d) (\d) (${groups})\b/($1 * 100 + $2 + $3) * $4/eg;
| "\(nameToNum|lpad(17)) = \(.)"</syntaxhighlight>
{{out}}
Exactly as for [[#Wren|Wren]].
 
=={{header|Julia}}==
s/\b(\d) 100 (\d\d) (${groups})\b/($1 * 100 + $2) * $3/eg;
<syntaxhighlight lang="julia">const stext = ["one", "two", "three", "four", "five",
s/\b(\d) 100 (\d) (${groups})\b/($1 * 100 + $2) * $3/eg;
"six", "seven", "eight", "nine"]
s/\b(\d) 100 (${groups})\b/$1 * $2 * 100/eg;
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(
s/\b100 (\d\d) (\d) (${groups})\b/(100 + $1 + $2) * $3/eg;
stext, teentext, tenstext, ordstext, ["minus", "and", "hundred", "thousand", "zero"]
s/\b100 (\d\d) (${groups})\b/(100 + $1) * $2/eg;
) s/\b100 (\d) (${groups})\b/(100 + $1) * $2/eg;
canon(word) = replace(lowercase(word), r"\-|\,|\.|\:" => "")
s/\b100 (${groups})\b/$1 * 100/eg;
isnumeric(word) = canon(word) in allnumeric
 
function parsenumericphrases(txt)
s/\b(\d\d) (\d) (${groups})\b/($1 + $2) * $3/eg;
words = split(strip(txt), r"(\s+)|(\s*\-\s*)")
s/\b(\d{1,2}) (${groups})\b/$1 * $2/eg;
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)
s/\b(\d\d) (\d) 100\b/($1 + $2) * 100/eg;
n = something(findfirst(x -> x == word, stext), 0)
s/\b(\d{1,2}) 100\b/$1 * 100/eg;
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
# Date anomolies: nineteen eighty-four and twenty thirteen
s/\b(\d{2}) (\d{2})\b/$1 * 100 + $2/eg;
 
function summils(word, miltotal, onestotal)
s/((?:${num} )*${num})/sum(split(" ",$1))/eg;
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)
print $orig, " => ", $_, "\n";
phrasepairs, outputphrases = parsenumericphrases(txt), String[]
}</lang>
for phrase in phrasepairs
Here is a sample '''input''' file:
if phrase[1] # numeric phrase
<pre>
wordarray, sign, onestotal, miltotal = phrase[2], 1, 0, 0
# For numbers between 21 and 99 inclusive, we're supposed to use a hyphen,
for word in wordarray
# but the bank still cashes our check without the hyphen:
onestotal = sumones(word, onestotal)
Seventy-two dollars
onestotal = sumhundreds(word, onestotal)
Seventy two dollars
miltotal, onestotal = summils(word, miltotal, onestotal)
 
end
# For numbers bigger than 100, we're not supposed to use "and,"
push!(outputphrases, string(sign * (onestotal + miltotal)))
# except we still use "and" anyway, e.g.,
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
A Hundred and One Dalmatians
One Hundred One Dalmatians
Hundred and One Dalmatians
One Thousand and One Nights
Two Thousand and One: A Space Odyssey
Four Score And Seven Years Ago
 
twelve dozen is one hundred forty-four, aka one gross
# Date anomolies
two hundred pairs of socks
Twenty Thirteen
Always give one hundred and ten percent effort
Nineteen Eighty-Four
Change due: zero dollars and thirty-seven cents
 
One hour, fifty-nine minutes, forty point two seconds
# Maximum value an "unsigned long int" can hold on a 32-bit machine = 2^32 - 1
Two Thousand Nineteen
# define ULONG_MAX 4294967295
Two Thousand Zero Hundred and Nineteen
four billion, two hundred ninety-four million, nine hundred sixty-seven thousand, two hundred ninety five
Two Thousand Ten Nine
 
one thousand one
# Max positive integer on 32-bit Perl is 9_007_199_254_740_992 = 2^53
ninety nine thousand nine hundred ninety nine
# Use Math::BigInt if you need more.
five hundred and twelve thousand, six hundred and nine
# Note Perl usually stringifies to 15 digits of precision and this has 16
two billion, one hundred
Nine quadrillion, seven trillion, one hundred ninety-nine billion, two hundred fifty-four million, seven hundred forty thousand, nine hundred ninety two
 
Nine Hundred Ninety-Nine
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
Seven Million Seven Hundred Seventy-Seven Thousand Seven Hundred Seventy-Seven
"""
Ninety-Nine Trillion Nine Hundred Ninety-Nine Billion Nine Hundred Ninety-Nine Million Nine Hundred Ninety-Nine Thousand Nine Hundred Ninety-Nine
 
for txt in split(strip(examples), r"\n")
ninety-nine
println(txt, " => ", texttointeger(txt))
three hundred
end
three hundred and ten
</syntaxhighlight>{{out}}
one thousand, five hundred and one
twelve thousand, six hundred and nine
five hundred and twelve thousand, six hundred and nine
forty-three million, one hundred and twelve thousand, six hundred and nine
two billion, one hundred
 
zero
eight
one hundred
one hundred twenty three
one thousand one
ninety nine thousand nine hundred ninety nine
one hundred thousand
nine billion one hundred twenty three million four hundred fifty six thousand seven hundred eighty nine
one hundred eleven billion one hundred eleven
</pre>
And here is the resulting '''output''' file:
<pre>
One Hundred and One Dalmatians => 101 Dalmatians
# For numbers between 21 and 99 inclusive, we're supposed to use a hyphen,
Two Thousand and One: A Space Odyssey => 2001: A Space Odyssey
# but the bank still cashes our check without the hyphen:
Four Score And Seven Years Ago => 4 Score 7 Years Ago
Seventy-two dollars => 72 dollars
twelve dozen is one hundred forty-four, aka one gross => 12 dozen is 144, aka 1 gross
Seventy two dollars => 72 dollars
two hundred pairs of socks => 200 pairs of socks
 
Always give one hundred and ten percent effort => Always give 110 percent effort
# For numbers bigger than 100, we're not supposed to use "and,"
Change due: zero dollars and thirty-seven cents => Change due: 0 dollars and 37 cents
# except we still use "and" anyway, e.g.,
One hour, fifty-nine minutes, forty point two seconds => 1 hour, 59 minutes, 40 point 2 seconds
One Hundred and One Dalmatians => 101 dalmatians
Two Thousand Nineteen => 2019
A Hundred and One Dalmatians => a 101 dalmatians
OneTwo Thousand Zero Hundred Oneand DalmatiansNineteen => 101 dalmatians2019
Two Thousand Ten Nine => 2019
Hundred and One Dalmatians => 101 dalmatians
Oneone Thousandthousand and One Nightsone => 1001 nights
ninety nine thousand nine hundred ninety nine => 99999
Two Thousand and One: A Space Odyssey => 2001 : a space odyssey
five hundred and twelve thousand, six hundred and nine => 512609
 
two billion, one hundred => 2000000100
# Date anomolies
Twenty Thirteen => 2013
Nineteen Eighty-Four => 1984
 
# Maximum value an "unsigned long int" can hold on a 32-bit machine = 2^32 - 1
# define ULONG_MAX 4294967295
four billion, two hundred ninety-four million, nine hundred sixty-seven thousand, two hundred ninety five => 4294967295
 
# Max positive integer on 32-bit Perl is 9_007_199_254_740_992 = 2^53
# Use Math::BigInt if you need more.
# Note Perl usually stringifies to 15 digits of precision and this has 16
Nine quadrillion, seven trillion, one hundred ninety-nine billion, two hundred fifty-four million, seven hundred forty thousand, nine hundred ninety two => 9.00719925474099e+015
 
Nine Hundred Ninety-Nine => 999
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
Seven Million Seven Hundred Seventy-Seven Thousand Seven Hundred Seventy-Seven => 7777777
Ninety-Nine Trillion Nine Hundred Ninety-Nine Billion Nine Hundred Ninety-Nine Million Nine Hundred Ninety-Nine Thousand Nine Hundred Ninety-Nine => 99999999999999
 
ninety-nine => 99
three hundred => 300
three hundred and ten => 310
one thousand, five hundred and one => 1501
twelve thousand, six hundred and nine => 12609
five hundred and twelve thousand, six hundred and nine => 512609
forty-three million, one hundred and twelve thousand, six hundred and nine => 43112609
two billion, one hundred => 2000000100
 
zero => 0
eight => 8
one hundred => 100
one hundred twenty three => 123
one thousand one => 1001
ninety nine thousand nine hundred ninety nine => 99999
one hundred thousand => 100000
nine billion one hundred twenty three million four hundred fifty six thousand seven hundred eighty nine => 9123456789
one hundred eleven billion one hundred eleven => 111000000111
</pre>
 
=={{header|Perl 6Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.2
{{works with|niecza|2013-05-18}}
<lang perl6>my $DEBUG = False;
 
val names = mapOf<String, Long>(
constant @M = ('ones', 'thousand',
"one" to 1,
((<m b tr quadr quint sext sept oct non>,
"two" to 2,
(map { ('', <un duo tre quattuor quin sex septen octo novem>).flat X~ $_ },
"three" to 3,
<dec vigint trigint quadragint quinquagint sexagint septuagint octogint nonagint>),
"four" to 4,
'cent').flat X~ 'illion')).flat;
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9,
"ten" to 10,
"eleven" to 11,
"twelve" to 12,
"thirteen" to 13,
"fourteen" to 14,
"fifteen" to 15,
"sixteen" to 16,
"seventeen" to 17,
"eighteen" to 18,
"nineteen" to 19,
"twenty" to 20,
"thirty" to 30,
"forty" to 40,
"fifty" to 50,
"sixty" to 60,
"seventy" to 70,
"eighty" to 80,
"ninety" to 90,
"hundred" to 100,
"thousand" to 1_000,
"million" to 1_000_000,
"billion" to 1_000_000_000,
"trillion" to 1_000_000_000_000L,
"quadrillion" to 1_000_000_000_000_000L,
"quintillion" to 1_000_000_000_000_000_000L
)
 
val zeros = listOf("zero", "nought", "nil", "none", "nothing")
constant %M = @M Z=> (1, 1000, 1000000 ... *);
 
fun nameToNum(name: String): Long {
grammar Number-Names {
var text = name.trim().toLowerCase()
token TOP { ^ [.*? <number>]* .* $ }
val isNegative = text.startsWith("minus ")
if (isNegative) text = text.drop(6)
if (text.startsWith("a ")) text = "one" + text.drop(1)
val words = text.split(",", "-", " and ", " ").filter { it != "" }
 
val size = words.size
method returns {
if (size == 1 && words[0] in zeros) return 0L
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);
}
 
var multiplier = 1L
token gotsome($oldself) {
var lastNum = 0L
<?{ self.pos != $oldself.pos }>
var sum = 0L
for (i in size - 1 downTo 0) {
val num: Long? = names[words[i]]
if (num == null)
throw IllegalArgumentException("'${words[i]}' is not a valid number")
else if (num == lastNum)
throw IllegalArgumentException("'$name' is not a well formed numeric string")
else if (num >= 1000) {
if (lastNum >= 100)
throw IllegalArgumentException("'$name' is not a well formed numeric string")
multiplier = num
if (i == 0) sum += multiplier
} else if (num >= 100) {
multiplier *= 100
if (i == 0) sum += multiplier
} else if (num >= 20) {
if (lastNum in 10..90)
throw IllegalArgumentException("'$name' is not a well formed numeric string")
sum += num * multiplier
} else {
if (lastNum in 1..90)
throw IllegalArgumentException("'$name' is not a well formed numeric string")
sum += num * multiplier
}
lastNum = num
}
 
tokenif number(isNegative {&& :isum «== -sum)
return Long.MIN_VALUE
:my $*SOFAR = 0;
else if (sum < 0L)
[
throw IllegalArgumentException("'$name' is outside the range of a Long integer")
| '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>
}
 
return if (isNegative) -sum else sum
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>
}
 
fun main(args: Array<String>) {
token hundreds { :i
val names = arrayOf(
[
"none",
| <date> <!!{ !$*SOFAR }> { make $<date>.ast }
"one",
| <ones> ['-'|\s*] 'hundred' { make $<ones>.ast * 100 }
"twenty-five",
| <?{ not $*SOFAR }>
"minus one hundred and seventeen",
<tweeny>['-'|\s*] 'hundred' { make $<tweeny>.ast * 100 }
"hundred and fifty-six",
| '' { make 0 }
"minus two thousand two",
]
"nine thousand, seven hundred, one",
<.returns>
"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) println("${"%20d".format(nameToNum(name))} = $name")
}</syntaxhighlight>
 
{{out}}
token tweens($c = 0) { :i
<pre>
:my $*SOFAR = $c;
0 = none
\s*
1 = one
[
| 'ten' 25 = { make 10 }twenty-five
-117 = minus one hundred and seventeen
| <teens> <!before \s*'hundred'> { make $<teens>.ast }
156 = hundred and fifty-six
| <ones> \s+ 'and' \s+ <tens> { make $<ones>.ast + $<tens>.ast }
-2002 = minus two thousand two
| <scores> \s+ 'and' \s+ <ones> { make $<scores>.ast + $<ones>.ast }
9701 = nine thousand, seven hundred, one
| <scores> \s+ 'and' \s+ <tweeny> { make $<scores>.ast + $<tweeny>.ast }
-626814 = minus six hundred and twenty six thousand, eight hundred and fourteen
| <tens>[['-'|\s*['and'\s*]?]<ones>]? { make $<tens>.ast + ($<ones> ?? $<ones>.ast !! 0) }
| <ones> 4700386 = four million, seven hundred thousand, three hundred and { make $<ones>.ast }eighty-six
51252017184 = fifty-one billion, two hundred and fifty-two million, seventeen thousand, one hundred eighty-four
| <scores> { make $<scores>.ast }
201021002001 = two hundred and one billion, twenty-one million, two thousand and one
| 'and'\s+ <?{ $c }> <tweens> { make $<tweens>.ast }
-300000009401031 = minus three hundred trillion, nine million, four hundred and one thousand and thirty-one
| (\d+[\.\d+]?) <?{ !$c }> { make +$0 }
17000000000000137 = seventeen quadrillion, one hundred thirty-seven
| '' { make 0 }
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
\s*
</pre>
<.returns>
}
 
=={{header|Nim}}==
token tweeny {
{{trans|Kotlin}}
[
<syntaxhighlight lang="nim">import re, sequtils, strformat, strutils, tables
| <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) }
]
}
 
const Names = {"one": 1u64,
token date { :i
"two": 2u64,
<tweeny>
"three": 3u64,
[
| 'ten' "four": { make $<tweeny>.ast * 100 + 10 }4u64,
"five": 5u64,
| <teens> <!before \s*'hundred'> { make $<tweeny>.ast * 100 + $<teens>.ast }
"six": 6u64,
| <tens>[['-'|\s*]<ones>]? { make $<tweeny>.ast * 100 + $<tens>.ast + ($<ones> ?? $<ones>.ast !! 0) }
"seven": 7u64,
| ['ought'|oh?][\s+|\-]<ones> { make $<tweeny>.ast * 100 + $<ones>.ast }
"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 | "
token scores { :i
const Zeros = ["zero", "nought", "nil", "none", "nothing"]
[
| ['one'|'a']?['-'|\s*] 'score' { make 20 }
| 'two' ['-'|\s*] 'score' { make 40 }
| 'three' ['-'|\s*] 'score' { make 60 }
| 'four' ['-'|\s*] 'score' { make 80 }
]
<.returns>
}
 
template emitError(msg: string) = raise newException(ValueError, msg)
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>
}
 
proc nameToNum(name: string): int64 =
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>
}
 
var text = name.strip().toLowerAscii
token zillions { :i
let isNegative = text.startsWith("minus ")
[
if isNegative: text.delete(0, 5)
| (\w+) <?{ %M{lc ~$0} }> { make +%M{lc ~$0} }
if text.startsWith("a"):
| <quantnoun> { make $<quantnoun>.ast }
text = "one" & text[1..^1]
| '' { make 1 }
let words = text.split(Seps).filterIt(it.len != 0)
]
if words.len == 1 and words[0] in Zeros:
<.returns>
}return 0
 
var
token quantnoun { :i
multiplier = 1u64
\s*
lastNum, sum = 0u64
[
for i in countdown(words.high, 0):
| 'pair's? ' of'? { make 2 }
let num = Names.getOrDefault(words[i], 0)
| 'dozen' { make 12 }
if num == 0:
| 'gross' ' of'? { make 144 }
emitError(&"'{words[i]}' is not a valid number")
| '' { make 1 }
elif num == lastNum:
]
emitError(&"'{name}' is not a well formed numeric string")
<.returns>
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:
sub commify($_) {
return int64.low
/\d\d\d\d\d/
if sum > uint64(int64.high):
?? .flip.subst(/\d\d\d<?before \d>/, -> $/ {$/~','},:g).flip
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>
 
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> 0 = none
<pre>Seventy-two dollars
1 = one
==> 72 dollars
25 = twenty-five
Seventy two dollars
-117 = minus one hundred and seventeen
==> 72 dollars
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}}==
<syntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
use utf8;
binmode STDOUT, ':utf8';
 
my $phrases_with_numbers = <<'END';
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
Four Score And Seven Years Ago
math one-oh-one
twelve dozen is one hundred forty-four, aka one gross
==> math 101
two hundred pairs of socks
Charlemagne died in eight-fourteen.
Always give one hundred and ten percent effort
==> Charlemagne died in 814.
Change due: zero dollars and thirty-seven cents
ten sixty-six
 
==> 1066
One hour, fifty-nine minutes, forty point two seconds
Nineteen Ought Three
π ≅ three point one four one five nine
==> 1903
END
Nineteen Eighty-Four
 
==> 1984
my $pure_numbers = <<'END';
Twenty Thirteen
Twenty Nineteen
==> 2013
Two Thousand Nineteen
four billion, two hundred ninety-four million, nine hundred sixty-seven thousand, two hundred ninety five
Two Thousand Zero Hundred and Nineteen
==> 4,294,967,295
Two Thousand Ten Nine
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
one thousand one
Nine Hundred Ninety-Nine
ninety nine thousand nine hundred ninety nine
==> 999
five hundred and twelve thousand, six hundred and nine
two billion, one hundred
 
One Thousand One Hundred Eleven
==> 1111
Eleven Hundred Eleven
one hundred eleven billion one hundred eleven
==> 1111
Eight Thousand Eight Hundred Eighty-Eight
==> 8888
Eighty-Eight Hundred Eighty-Eight
 
==> 8888
one quadrillion, two trillion, three billion, four million, five thousand six
Seven Million Seven Hundred Seventy-Seven Thousand Seven Hundred Seventy-Seven
END
==> 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
my %nums = (
==> 99,999,999,999,999
zero => 0, one => 1, two => 2, three => 3,
ninety-nine
four => 4, five => 5, six => 6, seven => 7,
==> 99
eight => 8, nine => 9, ten => 10, eleven => 11,
three hundred
twelve => 12, thirteen => 13, fourteen => 14, fifteen => 15,
==> 300
sixteen => 16, seventeen => 17, eighteen => 18, nineteen => 19,
three hundred and ten
twenty => 20, thirty => 30, forty => 40, fifty => 50,
==> 310
sixty => 60, seventy => 70, eighty => 80, ninety => 90,
one thousand, five hundred and one
hundred => 100, thousand => 1_000, million => 1_000_000,
==> 1501
billion => 1_000_000_000, trillion => 1_000_000_000_000,
twelve thousand, six hundred and nine
quadrillion => 1_000_000_000_000_000
==> 12,609
);
five hundred and twelve thousand, six hundred and nine
 
==> 512,609
# Groupings for thousands, millions, ... quadrillions
forty-three million, one hundred and twelve thousand, six hundred and nine
my $groups = qr/\d{4}|\d{7}|\d{10}|\d{13}|\d{16}/;
==> 43,112,609
 
two billion, one hundred
sub sum {
==> 2,000,000,100
my($values) = @_;
zero
my $sum = 0;
==> 0
$sum += $_ for split ' ', $values;
eight
$sum;
==> 8
}
one hundred
 
==> 100
sub squeeze {
one hundred twenty three
my($str) = @_;
==> 123
$str =~ s/[\-\s]+/ /g;
one thousand one
$str =~ s/^\s*(.*?)\s*$/$1/r;
==> 1001
}
ninety nine thousand nine hundred ninety nine
 
==> 99,999
# commify larger numbers for readabilty
one hundred thousand
sub comma {
==> 100,000
my($i) = @_;
nine billion one hundred twenty three million four hundred fifty six thousand seven hundred eighty nine
return $i if length($i) < 5;
==> 9,123,456,789
reverse ((reverse $i) =~ s/(.{3})/$1,/gr) =~ s/^,//r
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
sub numify {
==> sing a song of sixpence, a pocket full of rye, 24 blackbirds baked in a pie
my($str) = @_;
Fourscore and seven years ago, our four fathers...
 
==> 87 years ago, our 4 fathers...
$str =~ tr/A-Z/a-z/;
The Ninety and Nine
$str = squeeze($str);
==> The 99
 
Seven Brides for Seven Brothers
$str =~ s/(.)([[:punct:]])/$1 $2/g;
==> 7 Brides for 7 Brothers
 
Cheaper by the Dozen
foreach my $key (keys %nums) { $str =~ s/ \b $key \b /$nums{$key}/gx }
==> Cheaper by the 12
 
five dozen roses
$str =~ s/(\d+) \s+ (?=\d)/$1/gx if $str =~ /point (\d )+/;
==> 60 roses
$str =~ s/(\d+) \s+ score / $1 * 20 /egx;
a dozen dozen roses
 
==> 144 roses
$str =~ s/(\d) (?:,|and) (\d)/$1 $2/g;
two gross of eggs
 
==> 288 eggs
$str =~ s/\b (\d) \s+ 100 \s+ (\d\d) \s+ (\d) \s+ ($groups) \b / ($1 * 100 + $2 + $3) * $4 /egx;
two hundred pairs of socks
$str =~ s/\b (\d) \s+ 100 \s+ (\d{1,2}) \s+ ($groups) \b / ($1 * 100 + $2) * $3 /egx;
==> 400 socks
$str =~ s/\b (\d) \s+ 100 \s+ ($groups) \b / $1 * 100 * $2 /egx;
The First Noël
$str =~ s/\b \s+ 100 \s+ (\d\d) \s+ (\d) \s+ ($groups) \b / ($1 + 100 + $2) * $3 /egx;
==> The 1st Noël
$str =~ s/\b \s+ 100 \s+ (\d{1,2}) \s+ ($groups) \b / ($1 + 100 ) * $2 /egx;
second place
$str =~ s/\b \s+ 100 \s+ ($groups) \b / $1 * 100 /egx;
==> 2nd place
$str =~ s/\b (\d\d) \s+ (\d) \s+ ($groups) \b / ($1 + $2) * $3 /egx;
Forty-second Street
$str =~ s/\b (\d{1,2}) \s+ ($groups) \b / $1 * $2 /egx;
==> 42nd Street
$str =~ s/\b (\d\d) \s+ (\d) \s+ 100 \b / ($1 + $2) * 100 /egx;
the twenty-third Psalm
$str =~ s/\b (\d{1,2}) \s+ 100 \b / $1 * 100 /egx;
==> the 23rd Psalm
$str =~ s/\b (\d{2}) \s+ (\d{2}) \b / $1 * 100 + $2 /egx;
The Fourth Estate
 
==> The 4th Estate
$str =~ s/((?:\d+ )*\d+)/sum $1/eg;
The Fifth Essence
 
==> The 5th Essence
$str =~ s/(\d+) \s+ pairs.of / $1 * 2 /egx;
The sixth sick shiek's sixth sheep's sick.
$str =~ s/(\d+) \s+ dozen / $1 * 12 /egx;
==> The 6th sick shiek's 6th sheep's sick.
$str =~ s/(\d+) \s+ point \s+ (\d+) / $1.$2 /gx;
in seventh heaven
$str =~ s/(\d+) \s+ percent / $1% /gx;
==> in 7th heaven
$str =~ s/(\d+) \s+ dollars / \$$1 /gx;
The Eighth Wonder of the World!
$str =~ s/(\d+) \s+ cents / $1¢ /gx;
==> The 8th Wonder of the World!
 
Malher's Ninth Symphony
squeeze $str;
==> Malher's 9th Symphony
}
a tenth of all he had
 
==> a 10th of all he had
say $_ . ' --> ' . numify($_) for grep { $_ } split "\n", $phrases_with_numbers;
the eleventh hour
say $_ . ' --> ' . comma numify($_) for grep { $_ } split "\n", $pure_numbers;</syntaxhighlight>
==> the 11th hour
<pre>One Hundred and One Dalmatians --> 101 dalmatians
Twelfth Night
Two Thousand and One: A Space Odyssey --> 2001 : a space odyssey
==> 12th Night
Four Score And Seven Years Ago --> 87 years ago
Friday the Thirteenth
twelve dozen is one hundred forty-four, aka one gross --> 144 is 144 , aka 1 gross
==> Friday the 13th
two hundred pairs of socks --> 400 socks
Twentieth-Century Fox
Always give one hundred and ten percent effort --> always give 110% effort
==> 20th-Century Fox
Change due: zero dollars and thirty-seven cents --> change due : $0 and 37¢
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
One hour, fifty-nine minutes, forty point two seconds --> 1 hour , 509 minutes , 40.2 seconds
==> 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>
π ≅ 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
one quadrillion, two trillion, three billion, four million, five thousand six --> 1,002,003,004,005,006</pre>
 
=={{header|Phix}}==
Uses [[Number_names#Phix|Number_names]] as an executable library.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Names_to_numbers.exw
-- ---------------------------------
--</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<span style="color: #000000;">negmul</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">total</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<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>
<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>
<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;">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>
<span style="color: #000000;">total</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">hund</span>
<span style="color: #000000;">hund</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">tens</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">10</span>
<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>
<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>
<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>
<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>
<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>
<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>
<span style="color: #000000;">tens</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">10</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<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>
<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>
<span style="color: #000000;">hund</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">k</span>
<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>
<span style="color: #000000;">hund</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">k</span>
<span style="color: #008080;">else</span>
<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>
<span style="color: #000000;">hund</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<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>
<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>
<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>
<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>
<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>
<span style="color: #008080;">else</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: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<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>
<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">
99 <==> ninety-nine
300 <==> three hundred
310 <==> three hundred and ten
417 <==> four hundred and seventeen
1501 <==> one thousand, five hundred and one
12609 <==> twelve thousand, six hundred and nine
200000000000100 <==> two hundred trillion, and one hundred
999999999999999 <==> nine hundred and ninety-nine trillion, nine hundred and ninety-nine billion, nine hundred and ninety-nine million, nine hundred and ninety-nine thousand, nine hundred and ninety-nine
-123456787654321 <==> minus one hundred and twenty-three trillion, four hundred and fifty-six billion, seven hundred and eighty-seven million, six hundred and fifty-four thousand, three hundred and twenty-one
102003000400005 <==> one hundred and two trillion, three billion, four hundred thousand, and five
1020030004 <==> one billion, twenty million, thirty thousand, and four
102003 <==> one hundred and two thousand, and three
102 <==> one hundred and two
1 <==> one
0 <==> zero
-1 <==> minus one
-99 <==> minus ninety-nine
-1501 <==> minus one thousand, five hundred and one
1234 <==> one thousand, two hundred and thirty-four
12.34 <==> twelve point three four
10000001.2 <==> ten million, and one point two
0.001 <==> zero point zero zero one
-2.7182818 <==> minus two point seven one eight two eight one eight
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
</pre>
 
=={{header|Python}}==
Line 1,021 ⟶ 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,073 ⟶ 1,903:
num = int_from_words(txt)
print('%12i <%s> %s' % (n, '==' if n == num else '??', txt))
print('')</langsyntaxhighlight>
{{out}}
<pre>##
Line 1,103 ⟶ 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,108 ⟶ 2,006:
Extension of the [[Number_names#Racket | number to names]] code:
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 1,173 ⟶ 2,071:
(printf "~s <-> ~a\n" n eng)
(printf "Fail: ~s -> ~a -> ~s\n" n eng n2)))
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,188 ⟶ 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,222 ⟶ 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,248 ⟶ 2,266:
break if n==0
n /= -10
end</langsyntaxhighlight>
 
{{out}}
Line 1,283 ⟶ 2,301:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func names_to_number(str) {
 
static nums = Hash.new(
Line 1,301 ⟶ 2,319:
 
# Groupings for thousands, millions, ..., quintillions
static groups = /\d{4}|\d{7}|\d{10}|\d{13}|1\d{1516}|1\d{1819}/;
 
# Numeral or e-notation
static num = /\d+|\d+e\+\d+/;
 
str.trim!; # remove leading and trailing whitespace
Line 1,316 ⟶ 2,334:
 
# tokenize other punctuation and symbols
str.gsub!(/\$(.)/, {|a| '"$ ' + #{a}" }); # prefix
str.gsub!(/(.)([;:%'',])/, {|a,b| "#{a} + ' ' + #{b}"}); # suffix
 
nums.each { |key, value| str.gsub!(Regex.new('\b' + key + '\b'), value) };
Line 1,328 ⟶ 2,346:
Regex.new('\b(\d) 100 (\d\d) (' + groups + ')\b'),
Regex.new('\b(\d) 100 (\d) (' + groups + ')\b'),
Regex.new('\b100 b(\d\d) (\d)100 (' + groups + ')\b'),
Regex.new('\b100 (\d\d) (\d) (' + groups + ')\b'),
Regex.new('\b100 (\d\d) (' + groups + ')\b'),
Line 1,351 ⟶ 2,369:
str.gsub!(/\b(\d\d) (\d) 100\b/, {|a,b| (a.to_i + b.to_i) * 100});
str.gsub!(/\b(\d{1,2}) 100\b/, {|a| (a.to_i * 100) });
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 });
}</syntaxhighlight>
};</lang>
 
Usage:
<langsyntaxhighlight lang="ruby">ARGF.each { |line|
say "#{line.chomp.dump} --> #{names_to_number(line).dump}";
}</langsyntaxhighlight>
 
Sample:
Line 1,378 ⟶ 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,429 ⟶ 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,472 ⟶ 2,490:
foreach s $samples {
puts "$s => [name2num $s]"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,512 ⟶ 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}}==
<syntaxhighlight 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",
"thirty","forty","fifty","sixty","seventy","eighty","ninety",
"hundred","thousand","million","billion", "trillion")
.zip([0..20].chain([30..90,10]).walk().append(
100,1000,1000000,1000000000,1000000000000))
.toDictionary();
 
fcn stringToNumber(s){
s=s.toLower().replace(",","").replace(" and "," ").replace("-"," ");
words,minus,total,hund,prev := s.split(), 1,0,0,0;
if(not words) return(0);
if(words[0]=="minus"){ minus=-1; words=words[1,*]; }
foreach w in (words){
n:=names.find(w);
if(Void==n) throw(Exception.ValueError("I don't know "+w));
if(n<100){
dn,dp := n.numDigits,prev.numDigits; // 0,1,2 and 0,1,2,3,...
if(dp<3)
if((dn==dp==1) or dn==0 or dp==0) hund*=10;
else if(dn==2) hund*=100;
hund+=n;
}
else if(n==100) hund*=n;
else{ total+=hund*n; hund=0; }
prev=n;
}
minus*(total + hund)
}</syntaxhighlight>
<syntaxhighlight 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",
"six thousand Nineteen Eighty-Four",
"","zero","zero zero one","one zero","one zero two","one one three",
"ninety one","one ninety","ninety ninety",
"minus four million, five hundred and forty-seven thousand",
"six million, seven hundred and sixty-six thousand and twenty-seven")){
println("\"%s\" is %,d".fmt(s,stringToNumber(s)));
}</syntaxhighlight>
{{out}}
<pre>
"eighty-five thousand and one " is 85,001
" one hundred and fifty-five thousand and nineteen" is 155,019
"one thousand, nine hundred and eighty-four" is 1,984
"Nineteen Eighty-Four" is 1,984
"six thousand Nineteen Eighty-Four" is 7,984
"" is 0
"zero" is 0
"zero zero one" is 1
"one zero" is 10
"one zero two" is 102
"one one three" is 113
"ninety one" is 91
"one ninety" is 190
"ninety ninety" is 9,090
"minus four million, five hundred and forty-seven thousand" is -4,547,000
"six million, seven hundred and sixty-six thousand and twenty-seven" is 6,766,027
</pre>
9,482

edits