[英]format currency in PHP and JavaScript
我正在客户端和服务器上进行一些计算,发现最终结果有所不同。
我在做什么错,获取代表货币的两位十进制浮点数的正确方法是什么?
考虑以下代码(不带格式的最终数字为1,785):
JS
var sum = parseFloat(8.50);
var tax = parseFloat(21.00);
var total = parseFloat(sum * (tax / 100));
var test = total.toFixed(2);
console.log(test);
PHP
$sum = (float)"8.50";
$tax = (float)"21.00";
$total = (float)($sum * ($tax / 100));
$test = number_format($total, 2, ".", "");
echo $test;
在JS中我得到1.78
而在PHP 1.79
JS
var sum = parseFloat(8.50);
var tax = parseFloat(21.00);
var total = Math.round(sum*tax) / 100;
PHP
$sum = (float)"8.50";
$tax = (float)"21.00";
$total = round($sum*$tax/100, 2);
1.785的数学正确舍入值为1.79,因此上面的代码为您提供了所需的内容。
您可以使用
function RoundNum(num, length) {
var number = Math.round(num * Math.pow(10, length)) / Math.pow(10, length);
return number;
}
您不应该使用浮点数来存储和计算货币值-使用整数,分辨率为1/100美分(或1美分或其他)。 一些财务应用程序更进一步-1/10 000。
因此,$ 1将作为10000存储在数据库中。
在计算完税金和总计并四舍五入结果之后,您可以将其转换为美元金额以进行演示。
var sum = 85000; // $8.50
var taxRate = 0.21; // 21%
var tax = sum * taxRate; // $1.785
console.log(Math.round(tax / 100) / 100); // $1.79
var cents = tax / 100; // 178.5 cents
var wholeCents = Math.round(cents); // 179 cents
var dollars = cents / 100; // $1.79
这是因为PHP的number_format将数字四舍五入,如果您不希望这样做,请考虑以下函数:
function numberFormatNotRound($n, $decs, $decPoint = '.', $thousandsSep = ',')
{
$decs ++;
$n = number_format($n, $decs, $decPoint, $thousandsSep);
$n = substr($n, 0, -1);
return $n;
}
PHPFiddle: http ://phpfiddle.org/lite/code/457c-00nv
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.