PHP:用文字表达数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11500088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: Express Number in Words
提问by anita.kcx
Is there a function that will express any given number in words?
有没有一个函数可以用文字表达任何给定的数字?
For example:
例如:
If a number is 1432, then this function will return "One thousand four hundred and thirty two".
如果数字是1432,则此函数将返回“一千四百三十二”。
回答by martindilling
Use the NumberFormatter classthat are in php ;)
使用php 中的NumberFormatter 类;)
$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
echo $f->format(1432);
That would output "one thousand four hundred thirty-two"
那将输出“一千四百三十二”
回答by Shahbaz
You can do this in many ways I am mentioning here two ways by using The NumberFormatter classas mentioned in Martindillinganswer (if you have php version 5.3.0 or higher and also PECL extension 1.0.0 or higher) or by using the following custom function.
您可以通过使用Martindilling回答中提到的 NumberFormatter 类(如果您有 php 版本 5.3.0 或更高版本以及 PECL 扩展 1.0.0 或更高版本)或使用以下自定义功能。
function convertNumberToWord($num = false)
{
$num = str_replace(array(',', ' '), '' , trim($num));
if(! $num) {
return false;
}
$num = (int) $num;
$words = array();
$list1 = array('', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
);
$list2 = array('', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', 'hundred');
$list3 = array('', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion',
'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quattuordecillion',
'quindecillion', 'sexdecillion', 'septendecillion', 'octodecillion', 'novemdecillion', 'vigintillion'
);
$num_length = strlen($num);
$levels = (int) (($num_length + 2) / 3);
$max_length = $levels * 3;
$num = substr('00' . $num, -$max_length);
$num_levels = str_split($num, 3);
for ($i = 0; $i < count($num_levels); $i++) {
$levels--;
$hundreds = (int) ($num_levels[$i] / 100);
$hundreds = ($hundreds ? ' ' . $list1[$hundreds] . ' hundred' . ' ' : '');
$tens = (int) ($num_levels[$i] % 100);
$singles = '';
if ( $tens < 20 ) {
$tens = ($tens ? ' ' . $list1[$tens] . ' ' : '' );
} else {
$tens = (int)($tens / 10);
$tens = ' ' . $list2[$tens] . ' ';
$singles = (int) ($num_levels[$i] % 10);
$singles = ' ' . $list1[$singles] . ' ';
}
$words[] = $hundreds . $tens . $singles . ( ( $levels && ( int ) ( $num_levels[$i] ) ) ? ' ' . $list3[$levels] . ' ' : '' );
} //end for loop
$commas = count($words);
if ($commas > 1) {
$commas = $commas - 1;
}
return implode(' ', $words);
}

![PHP Session 用于计算访问次数和重定向 if (session['visits']=1)](/res/img/loading.gif)