在 PHP 中,如何转换一个拼写数字的字符串,如“四十二”或“四十二”或“五千”或“一”,并转换为由数字组成的字符串,如“42”或“ 42”或“5000”或“1”。
我发现这可以将某些数字(它有一个上限)转换为拼写出来的版本,但我正试图做相反的事情。
<?php
/**
* Function: convert_number
*
* Description:
* Converts a given integer (in range [0..1T-1], inclusive) into
* alphabetical format ("one", "two", etc.)
*
* @int
*
* @return string
*
*/
function convert_number($number)
{
if (($number < 0) || ($number > 999999999))
{
throw new Exception("Number is out of range");
}
$Gn = floor($number / 1000000); /* Millions (giga) */
$number -= $Gn * 1000000;
$kn = floor($number / 1000); /* Thousands (kilo) */
$number -= $kn * 1000;
$Hn = floor($number / 100); /* Hundreds (hecto) */
$number -= $Hn * 100;
$Dn = floor($number / 10); /* Tens (deca) */
$n = $number % 10; /* Ones */
$res = "";
if ($Gn)
{
$res .= convert_number($Gn) . " Million";
}
if ($kn)
{
$res .= (empty($res) ? "" : " ") .
convert_number($kn) . " Thousand";
}
if ($Hn)
{
$res .= (empty($res) ? "" : " ") .
convert_number($Hn) . " Hundred";
}
$ones = array("", "One", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eightteen",
"Nineteen");
$tens = array("", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty",
"Seventy", "Eigthy", "Ninety");
if ($Dn || $n)
{
if (!empty($res))
{
$res .= " and ";
}
if ($Dn < 2)
{
$res .= $ones[$Dn * 10 + $n];
}
else
{
$res .= $tens[$Dn];
if ($n)
{
$res .= "-" . $ones[$n];
}
}
}
if (empty($res))
{
$res = "zero";
}
return $res;
}
$cheque_amt = 8747484 ;
try
{
echo convert_number($cheque_amt);
}
catch(Exception $e)
{
echo $e->getMessage();
}
?>
我将非常感谢任何帮助我弄清楚如何做到这一点,因为我很难过。
现在,我正在考虑使用 PHPis_numeric()
来检测它是否是数字,但是如何将它转换为数字呢?
更新: 这是一个更好的例子,因为它没有限制并且可以处理负数。但它正在做相反的事情。有人可以帮我得到这个代码来做相反的事情(将拼出的数字转换为数字)。