javascript可以计算百分比吗?

时间:2012-07-06 12:10:40

标签: jquery percentage

我们列出了一个庞大的费用库。有些人有10%(GST)税,有些人有#。##%税。

结果应如下打印:

$ 123.45 10%TOTAL:$ 135.8

$ 123.45 0%TOTAL:$ 123.45

$ 123.45 7%TOTAL:$ 132.10

要在我们的CMS中打印这些结果,我们使用元数据值和关键字:

%asset_metadata_Amount%    %asset_metadata_GST%   %asset_metadata_Custom_Tax%

如果'_GST'的值为空,它将打印'_Custom_Tax',如果它们都是空的,则不需要进行计算。

我知道ID可以帮助查询,所以:

<span id="row_1"><span id="abc">%asset_metadata_Amount%</span> <span id="def">%asset_metadata_GST%</span> <span id="xyz">%asset_metadata_Custom_Tax%</span> <span id="total"> # </span></span>

我需要提供一些澄清,向所有人道歉;可以使用关键字运行函数来执行乘法吗?即。代码可以写成

total = %_Amout% * 1.%_GST%

或者'%'符号会破坏脚本吗?

2 个答案:

答案 0 :(得分:3)

  

javascript可以计算百分比吗?

任何使用数学运算符的语言都可以计算百分比。在您的情况下,使用您的示例标记:

var baseAmount, taxRate, tax, total;

// Get the base amount, stripping off non-floating-point-number chars,
// convert to number
baseAmount = parseFloat($("#abc").text().replace(/[^0-9\.]/, ""));

// Same with the tax rate, divide by 100
taxRate = parseFloat($("#def").text().replace(/[^0-9\.]/, "")) / 100;

// Tax is baseAmount * taxRate
tax = baseAmount * taxRate;

// Add to base to get total
total = baseAmount + tax;

现在,你必须要小心IEEE-754浮点数的限制,这允许在(0.1 + 0.2 = 0.30000000000000004)中有一些不精确,但如果你做了一些Math.round的东西,你应该很好。

答案 1 :(得分:3)

JavaScript的:

$(function() {
    var rows = $(".row");
    rows.each(function(index, row) {
        var amount = parseFloat($(row).children(".amount").text());
        var gst = parseFloat($(row).children(".gst").text());
        var customTax = parseFloat($(row).children(".customTax ").text());
        var tax = (isNaN(gst) ? (!isNaN(customTax) ? customTax : 0) : gst);
        var totalSpan = $(row).children(".total");
        console.log("Amount: ", amount);
        console.log("Tax: ", tax);
        totalSpan.html("Total: " + (amount + amount * (isNaN(tax) ? 0 : tax) / 100).toFixed(2));
    });
});​

HTML:

<span id="row_1" class="row">
    <span class="amount">123.45</span>
    <span class="gst"></span> 
    <span class="customTax"></span> 
    <span class="total"><!-- # --></span>
</span>​

我还将其发布为jsfiddle:http://jsfiddle.net/FHMrW/1/

注意:我已将id替换为class属性,以支持多行。

编辑:根据来自@ t-j-crowder的评论,此处包含代码,并在总计上添加toFixed