我在php中使用数字格式化程序,它需要用货币格式化,也需要用文字格式化,问题是它需要格式化的值有十进制值,它给我的值为二千九百三十点零四和它应该是两千九百三十四美分,如果值有十进制它给我一个字面点这里是我的代码
$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
$formated = $f->format(2903.04);
请帮助我谢谢
答案 0 :(得分:0)
对于货币没有定义的拼写格式化程序,而you could probably write one我认为这可能有点过分。
你可以做的是将美元作为美分分成不同的值,将它们拼出来并合并它们。
首先,您 不 希望存储或计算具有浮点表示的货币。我最后要保存这一点,但在浮点错误出现之前,我甚至无法完成初始步骤。
$v = 2903.04;
$d = (int)$v; // casting to int discards decimal portion
$c = (int)(($v - $d) * 100);
var_dump($v, $d, ($v - $d) * 100, $c);
输出:
float(2903.04)
int(2903)
float(3.9999999999964)
int(3)
使用类似moneyphp/money的内容,将货币值存储为基本货币单位的整数。 [例如:$ 2903.04 == 290304]这可以避免上述错误,以及与舍入相关的混乱。此外,资金库将实施安全数学运算,以便在3个收件人中分配1.00美元而不会分割或丢失便士。
相反,让我们编写如下代码:
$a = 290304; // full amount in cents
$c = $a % 100; // cent remainder
$d = ($a - $c) / 100; // dollars
$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
var_dump(
$a, $d, $c,
sprintf("%s dollars and %s cents", $f->format($d), $f->format($c))
);
输出:
int(290304)
int(2903)
int(4)
string(54) "two thousand nine hundred three dollars and four cents"
答案 1 :(得分:0)
检查我的工作转换器:https://smctgroup.com/contracts/number.php
输入: 2903.04
输出:两百九十三比索和四仙塔斯
您可以将比索更改为美元
您可以使用此功能:
function makewords($numval)
{
$moneystr = "";
$num_arr = explode(".", $numval);
$decnum = $num_arr[1];
// handle the millions
$milval = (integer)($numval / 1000000);
if($milval > 0)
{
$moneystr = getwords($milval) . " Million";
}
// handle the thousands
$workval = $numval - ($milval * 1000000); // get rid of millions
$thouval = (integer)($workval / 1000);
if($thouval > 0)
{
$workword = getwords($thouval);
if ($moneystr == "")
{
$moneystr = $workword . " Thousand";
}
else
{
$moneystr .= " " . $workword . " Thousand";
}
}
// handle all the rest of the dollars
$workval = $workval - ($thouval * 1000); // get rid of thousands
$tensval = (integer)($workval);
if ($moneystr == "")
{
if ($tensval > 0)
{
$moneystr = getwords($tensval);
}
else
{
$moneystr = "Zero";
}
}
else // non zero values in hundreds and up
{
$workword = getwords($tensval);
$moneystr .= " " . $workword;
}
// plural or singular 'dollar'
$workval = (integer)($numval);
if ($workval == 1)
{
$moneystr .= " Peso";
}
else
{
$moneystr .= " Pesos";
}
// //My cents
// if ($workint > 0) {
// $moneystr .= " and ";
// if ($workint < 20) {
// $moneystr .= $ones[$workint];
// } elseif ($workint < 100) {
// $moneystr .= $tens[substr($workint, 0, 1)];
// $moneystr .= " ".$ones[substr($workint, 1, 1)];
// }
// }
// do the pennies - use printf so that we get the
// same rounding as printf
$workstr = sprintf("%3.2f",$numval); // convert to a string
$intstr = substr($workstr,strlen - 2, 2);
$workint = (integer)($intstr);
if($decnum>0) {
$moneystr .= " and ";
if ($workint == 0)
{
$moneystr .= "Zero";
}
else
{
$moneystr .= getwords($decnum);
}
if ($workint == 1)
{
$moneystr .= " Centavo";
}
else
{
$moneystr .= " Centavos";
}
}
// done - let's get out of here!
return $moneystr;
}