如果您想將一個整數轉換成英文單詞字符串,例如 29 -> twenty-nine,這裡有一個函數可以做到。
關於 fmod() 的使用說明
我使用浮點數 fmod() 而不是 % 運算符,因為 % 會將運算元轉換為 int,從而損壞 [-2147483648, 2147483647] 範圍之外的值。
我沒有處理「billion」,因為這個詞代表 10e9 或 10e12,取決於你問誰。
如果參數不代表整數,則該函數返回 '#'。
<?php
$nwords = array( "zero", "one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
"nineteen", "twenty", 30 => "thirty", 40 => "forty",
50 => "fifty", 60 => "sixty", 70 => "seventy", 80 => "eighty",
90 => "ninety" );
function int_to_words($x) {
global $nwords;
if(!is_numeric($x))
$w = '#';
else if(fmod($x, 1) != 0)
$w = '#';
else {
if($x < 0) {
$w = 'minus ';
$x = -$x;
} else
$w = '';
if($x < 21) $w .= $nwords[$x];
else if($x < 100) { $w .= $nwords[10 * floor($x/10)];
$r = fmod($x, 10);
if($r > 0)
$w .= '-'. $nwords[$r];
} else if($x < 1000) { $w .= $nwords[floor($x/100)] .' hundred';
$r = fmod($x, 100);
if($r > 0)
$w .= ' and '. int_to_words($r);
} else if($x < 1000000) { $w .= int_to_words(floor($x/1000)) .' thousand';
$r = fmod($x, 1000);
if($r > 0) {
$w .= ' ';
if($r < 100)
$w .= 'and ';
$w .= int_to_words($r);
}
} else { $w .= int_to_words(floor($x/1000000)) .' million';
$r = fmod($x, 1000000);
if($r > 0) {
$w .= ' ';
if($r < 100)
$word .= 'and ';
$w .= int_to_words($r);
}
}
}
return $w;
}
?>
用法
<?php
echo '目前有 '. int_to_words($count) . ' 位成員登入。';
?>