我不是一个Java专家,但我正在使用下面的代码进行计算。代码运行良好,但我需要将最终总数限制为2位小数,因为答案是£的数字。例如我想要123.45英镑,但我得到的数字是123.456英镑。
这是我的代码。需要知道在哪里以及放入什么来制作2位小数
<script>
jQuery(document).ready(function ($) {
var calculate = function () {
var total = 0.00;
// Check the chosen option of a select menu
var val1 = $('.iphorm_3_1').val();
if (val1 == '25 sqft') {
total += 17.94;
} else if (val1 == '35 sqft') {
total += 22.74;
} else if (val1 == '50 sqft') {
total += 29.94;
} else if (val1 == '75 sqft') {
total += 39.54;
} else if (val1 == '100 sqft') {
total += 45.54;
} else if (val1 == '125 sqft') {
total += 53.94;
} else if (val1 == '150 sqft') {
total += 59.94;
} else if (val1 == '200 sqft') {
total += 71.94;
}
// A second select menu
var val2 = $('.iphorm_3_2').val();
if (val2 == '1 week') {
total *= 1.00;
} else if (val2 == '2 weeks') {
total *= 2.00;
} else if (val2 == '3 weeks') {
total *= 3.00;
} else if (val2 == '4 weeks') {
total *= 4.00;
} else if (val2 == '5 weeks') {
total *= 5.00;
} else if (val2 == '6 weeks') {
total *= 6.00;
} else if (val2 == '7 weeks') {
total *= 7.00;
} else if (val2 == '8 weeks') {
total *= 8.00;
} else if (val2 == '9 weeks') {
total *= 9.00;
} else if (val2 == '10 weeks') {
total *= 10.00;
} else if (val2 == '11 weeks') {
total *= 11.00;
} else if (val2 == '12 weeks') {
total *= 12.00;
}
// A third select menu
var val3 = $('.iphorm_3_5').val();
if (val3 == 'Immediately') {
total += total/100*80-total;
} else if (val3 == 'Within a week') {
total += 0.00;
} else if (val3 == 'Within two weeks') {
total += 0.00;
} else if (val3 == 'Within a month') {
total += 0.00;
}
// Display the result to the user
$('#form-total').text('Total: $' + total);
// Set the value of the hidden field
$('input[name=iphorm_3_8]').val('£' + total);
};
// Calculate on page load
calculate();
// Recalculate when these select menus are changed
$('.iphorm_3_1, .iphorm_3_2, .iphorm_3_5').change(calculate);
});
</script>
答案 0 :(得分:1)
您可以使用
total = Math.round(total * 100) / 100;
答案 1 :(得分:0)
使用toFixed(2)
// Display the result to the user
$('#form-total').text('Total: $' + total.toFixed(2));
// Set the value of the hidden field
$('input[name=iphorm_3_8]').val('£' + total.toFixed(2));
或者您可以在显示之前设置值
total = total.toFixed(2);
// Display the result to the user
$('#form-total').text('Total: $' + total);
// Set the value of the hidden field
$('input[name=iphorm_3_8]').val('£' + total);