簡體   English   中英

計算中的小數位

[英]Decimal places in calculation

我絕不是Java專家,但我正在使用下面的代碼進行計算。 該代碼運行良好,但我需要將最終總數限制為2個小數位,因為答案是用£表示的數字。 例如,我想要123.45英鎊,但得到的數字如123.456英鎊。

這是我的代碼。 需要知道放置在什么地方和什么位置才能使小數點后兩位

 <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> 

您可以使用

total = Math.round(total * 100) / 100;

用於固定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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM