1

在此之前,我已经问过同样的问题并得到了答案,但我错了。我需要在不使用任何库的情况下将数字转换为单词,尤其是 Lingua::Numbers。

我找到了一个示例来分隔电话号码中的数字。然后我尝试在我的脚本中实现该示例。但它没有用。

这是我的脚本。

$x = "1104";
$x =~ s/1/ one /gi; #from 1-10, I, substitute number to words to words
$x =~ s/2/ two /gi;
$x =~ s/3/ three /gi;
$x =~ s/4/ four /gi;
$x =~ s/5/ five /gi;
$x =~ s/6/ six /gi;
$x =~ s/7/ seven /gi;
$x =~ s/8/ eight /gi;
$x =~ s/9/ nine /gi;
$x =~ s/10/ ten /gi;
$y = ($x{1}[thousand]?$x{1}[hundred and]?$x{2});  


    #then I will insert all my $x into $y.

$x =~ s/$x/$y/gi; #Here i substitute again to change all number to words

#that is my idea.

print "$x";

我试着先把它变成 4 位数。如果成功,那么我可以继续插入,直到有 7-8 位或更多。

4

1 回答 1

0

在代码中执行此操作更加直观。这是 C# 的开始,但需要进行最少的更改才能在几乎任何类 C 语言中工作:

string Speak(int num)
{
    if (num < 0) return "negative " + Speak(-num);
    if (num >= 1000000000) return Speak(num / 1000000000) + " billion " + Speak(num % 1000000000);
    if (num >= 1000000) return Speak(num / 1000000) + " million " + Speak(num % 1000000);
    if (num >= 1000) return Speak(num / 1000) + " thousand " + Speak(num % 1000);
    if (num >= 100) return Speak(num / 100) + " hundred " + Speak(num % 100);
    if (num >= 20)
    {
        switch (num / 10)
        {
            case 2: return "twenty " + Speak(num % 10);
            case 3: return "thirty " + Speak(num % 10);
            case 4: return "forty " + Speak(num % 10);
            case 5: return "fifty " + Speak(num % 10);
            case 6: return "sixty " + Speak(num % 10);
            case 7: return "seventy " + Speak(num % 10);
            case 8: return "eighty " + Speak(num % 10);
            case 9: return "ninety " + Speak(num % 10);
        }
    }
    switch (num)
    {
        case 0: return "";
        case 1: return "one";
        case 2: return "two";
        case 3: return "three";
        case 4: return "four";
        case 5: return "five";
        case 6: return "six";
        case 7: return "seven";
        case 8: return "eight";
        case 9: return "nine";
        case 10: return "ten";
        case 11: return "eleven";
        case 12: return "twelve";
        case 13: return "thirteen";
        case 14: return "fourteen";
        case 15: return "fifteen";
        case 16: return "sixteen";
        case 17: return "seventeen";
        case 18: return "eighteen";
        case 19: return "nineteen";
    }
    return "";
}

例子:

Speak("123000701") -> "one hundred twenty three million seven hundred one";

我将把它作为一个练习来添加对零、逗号和“和”字的支持。

于 2013-04-03T22:58:08.073 回答