简体   繁体   中英

How can I convert a number to text in Perl?

I need some code in my program which takes a number as input and converts it into corresponding text eg 745 to "seven hundred forty five".

Now, I can write code for this, but is there any library or existing code I can use?

From perldoc of Lingua::EN::Numbers :

use Lingua::EN::Numbers qw(num2en num2en_ordinal);

my $x = 234;
my $y = 54;
print "You have ", num2en($x), " things to do today!\n";
print "You will stop caring after the ", num2en_ordinal($y), ".\n";

prints:

You have two hundred and thirty-four things to do today!
You will stop caring after the fifty-fourth.

You need to look at this stackoverflow question

From the above-mentioned link:

perl -MNumber::Spell -e 'print spell_number(2);'

看一下Math :: BigInt :: Named模块。

You can try something like this:

#!/usr/bin/perl

use strict;
use warnings;

my %numinwrd = (
  0 => 'Zero', 1 => 'One', 2 => 'Two',   3 => 'Three', 4 => 'Four',
  5 => 'Five', 6 => 'Six', 7 => 'Seven', 8 => 'Eight', 9 => 'Nine',
);

print "The number when converted to words is 745=>".numtowrd(745)."\n";

sub numtowrd {
  my $num = shift;
  my $txt = "";  
  my @val = $num =~ m/./g;

  foreach my $digit (@val) {    
    $txt .= $numinwrd{$digit} . " ";   
  }

  return $txt;
}

The output is:

The number when converted to words is 745=>Seven Four Five 

另请参阅Nums2Words

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM