在js发票中舍入到小数点后2位

时间:2014-04-20 09:24:05

标签: javascript

我的发票js脚本完成并正常工作,但我无法弄清楚如何将总计四舍五入到2位小数。

JS:

var item = document.getElementById('item');
var item1 = document.getElementById('item1');
var item2 = document.getElementById('item2');
var item3 = document.getElementById('item3');

item.onchange = function() {
        price.innerHTML = "$" + this.value;
        qty.value = 1; //Order 1 by default.
        add();
    };
    qty.onchange = function() {
        add();
    }
item1.onchange = function() {
        price1.innerHTML = "$" + this.value;
        qty1.value = 1; //Order 1 by default.
        add();
    };
    qty1.onchange = function() {
        add();
    }
item2.onchange = function() {
        price2.innerHTML = "$" + this.value;
        qty2.value = 1; //Order 1 by default.
        add();
    };
    qty2.onchange = function() {
        add();
    }
item3.onchange = function () {
        price3.innerHTML = "$" + this.value;
        qty3.value = 1; //Order 1 by default.
        add();
    };
    qty3.onchange = function() {
        add();
    }
  function add() {
      var inputs = document.getElementsByTagName('input');
      var selects = document.getElementsByTagName('select');

      var total = 0;
      for (var i = 0; i < selects.length; i++) {
        var sum = 0;
        var price = (parseFloat(selects[i].value) )?parseFloat(selects[i].value):0;
        var qty = (parseFloat(inputs[i].value) )?parseFloat(inputs[i].value):0;
        sum += price * qty;
        total += sum * 1.06
        if(i == 0){
          document.getElementById('result').innerHTML = "$" + sum;
        }else{

          document.getElementById('result'+i).innerHTML = "$" + sum;
        }             
      };

      document.getElementById('Total').innerHTML = "$" + total;
  }

我试过3或4种方法,但由于我缺乏js的经验,我只是不能正确

3 个答案:

答案 0 :(得分:0)

使用:

.toFixed(2);

总计

像:

1.23898.toFixed(2); // 1.24

答案 1 :(得分:0)

你想要这样的smt:1.23756 - &gt; 1.24? 然后,您可以使用toFixed(num)

var num = 1.23756;
console.log(num.toFixed(2)); // 1.24

请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

答案 2 :(得分:0)

试试this: 将数字转换为字符串,只保留两位小数:

var num = 5.56789;
var n=num.toFixed(2);

n的结果将是:

5.57