Created
November 18, 2021 17:11
-
-
Save Gro-Tsen/dfb5ede39280d586aad517a10245d571 to your computer and use it in GitHub Desktop.
Convert a decimal number to its literal expression in English
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/local/bin/perl -w | |
# Convert a decimal number to its literal expression in English. | |
use strict; | |
use warnings; | |
use Getopt::Std; | |
my %opts; | |
getopts("u", \%opts); | |
my @units = ( "zero", "one", "two", "three", "four", | |
"five", "six", "seven", "eight", "nine" ); | |
my @teens = ( "ten", "eleven", "twelve", "thirteen", "fourteen", | |
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen" ); | |
my @tens = ( "", "ten", "twenty", "thirty", "forty", | |
"fifty", "sixty", "seventy", "eighty", "ninety" ); | |
sub name100 { | |
use integer; | |
my $n = shift; | |
die "Bad input to name100" unless $n >= 0 && $n < 100 && $n == ($n/10)*10+($n%10); | |
if ( $n < 10 ) { | |
return $units[$n]; | |
} elsif ( $n < 20 ) { | |
return $teens[$n%10]; | |
} else { | |
my $s = $tens[$n/10]; | |
$s .= "-".$units[$n%10]; | |
return $s; | |
} | |
} | |
sub name1000 { | |
use integer; | |
my $n = shift; | |
die "Bad input to name1000" unless $n >= 0 && $n < 1000 && $n == ($n/100)*100+($n%100); | |
if ( $n < 100 ) { | |
return name100($n); | |
} else { | |
my $s = $units[$n/100] . " hundred"; | |
if ( $n%100 == 0 ) { | |
} else { | |
$s .= ($opts{u}?" ":" and ").name100($n%100); | |
} | |
return $s; | |
} | |
} | |
sub namemillion { | |
use integer; | |
my $n = shift; | |
die "Bad input to namemillion" unless $n >= 0 && $n < 1000000 && $n == ($n/1000)*1000+($n%1000); | |
if ( $n < 1000 ) { | |
return name1000($n); | |
} else { | |
my $s = name1000($n/1000) . " thousand"; | |
my $t = name1000($n%1000); | |
$t = "and ".$t unless $t =~ /\band\b/ || $opts{u}; | |
$s .= " ".$t if $n%1000; | |
return $s; | |
} | |
} | |
sub namebillion { | |
use integer; | |
my $n = shift; | |
die "Bad input to namebillion" unless $n >= 0 && $n < 1000000000 && $n == ($n/1000000)*1000000+($n%1000000); | |
if ( $n < 1000000 ) { | |
return namemillion($n); | |
} else { | |
my $s = name1000($n/1000000) . " million"; | |
my $t = namemillion($n%1000000); | |
$t = "and ".$t unless $t =~ /\band\b/ || $opts{u}; | |
$s .= " ".$t if $n%1000000; | |
return $s; | |
} | |
} | |
binmode STDOUT, ":utf8"; | |
while ( <> ) { | |
chop; | |
printf "%s\n", namebillion($_); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment