无论输入采用什么格式,我都尝试使用 PHP 对其进行修改,因此输出始终保持一致,四舍五入到小数点后两位并带有美元符号。我的方法并不总是产生预期的结果,我想知道是否有人可以帮助我想出更强大的解决方案?
期望输出:
$num = "$12.00"; //output $12.00
$num = "125"; //output $125.00
$num = "$300"; //output $300.00
$num = "17.5"; //output $17.50
$num = "1,777.5"; //output $1777.50
我尝试过,但这并不适用于所有情况:
$num = "$" . str_replace("$", "", round($num,0)) . ".00";
我感谢任何建议!提前非常感谢!
$num = "$" . str_replace("$", "", round($num,0));
在此行中,在删除 $-符号之前进行舍入。我必须反过来:
$num = "$" . round(str_replace("$", "", $num),0);
编辑:为了获得你想要的输出,你可能想使用number_format()而不是round()
$num = "$" . number_format(str_replace("$", "", $num),2, '.', '');