[英]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.