我开发了一个代码,在其中添加值,最后根据您在表单中选择的项目减去最小值。大部分代码工作得很好但是当它显示总数时我遇到了问题。当我的值为7.25时,它将正常工作,但如果它是一个整数,它将只显示5.我希望它显示5.00。有什么建议吗?
<script language="JavaScript">
// All selected prices are stored on a array
var prices = [];
// A function to remove a item from an array
function remove(array, item) {
for (var i = 0, len = array.length; i < len; i++) {
if (array[i] == item) {
array.splice(i, 1);
return true;
}
}
return false;
}
function calculateSectedDues(checkbox, amount) {
// We add or remove the price as necesary
if (checkbox.checked) {
prices.push(amount);
} else {
remove(prices, amount);
}
// We sum all the prices
var total = 0;
for (var i = 0, len = prices.length; i < len; i++)
total += prices[i];
// We get the lower one
var min = Math.min.apply(Math, prices);
if(min == Infinity) { min = 0; }
// And substract it
total -= min;
// Please, don't access the DOM elements this way, use document.getElementById instead
document.grad_enroll_form.total.value = total;
}
</script>
答案 0 :(得分:4)
您可以使用JS的toFixed()
方法:
var min = 2;
min.toFixed(2); // returns 2.00
答案 1 :(得分:0)
if(parseInt(total) == total){
total += ".00";
}
或短标记:
total = parseInt(total) == total ? total + ".00" : total