如何将输出值更改为2位小数?

时间:2014-09-11 22:54:51

标签: jquery decimal calculator

我希望全部和数量的罐子以小数点后两位显示:

$('input').keyup(function () { // run anytime the value changes


var firstValue = parseFloat($('#width').val()); // get value of field
var secondValue = parseFloat($('#height').val());
var thirdValue = parseFloat($('#per-can').val()); // convert it to a float
var forthValue = parseFloat($('#cost').val());
var fithValue = parseFloat($('#size').val());

$('#added').html(firstValue * secondValue / thirdValue * forthValue);
$('#cans').html(firstValue * secondValue / thirdValue);

});

另外,作为一个额外的挑战,我可以有一个额外的输出,比如说'需要的最小罐',它会根据一个向上的方式显示数量 - 例如。如果罐数=> 1但是<2则需要最小罐数= 2?

这是我的小提琴:http://jsfiddle.net/5xzSy/485/任何人都可以根据这个例子帮助我吗?

1 个答案:

答案 0 :(得分:0)

这样的事情,也许是:

var canCount = firstValue * secondValue / thirdValue;

$('#added').html((canCount * forthValue).toFixed(2));
$('#cans').html(canCount.toFixed(2));

if (Math.ceil(canCount) < 2) {
    // show error that at least two are needed
}

作为一个额外的建议,您应该将变量命名为有意义的内容,就像我使用canCount一样。