将输出四舍五入到 2 位小数

时间:2021-06-16 14:50:07

标签: javascript

我编写了一个小型复利计算器。最后一个输出字段必须显示使用上述输入计算的金额。但它应该四舍五入到两位小数,我没有让它与我在网上找到的各种代码片段甚至 stackoverflow 一起使用。

var $button9 = $('.increment-btn5'); // button to call the function below
var $counter1 = $('.counter1'); // First input
var $counter2 = $('.counter2'); // obsolete var at the moment
var $counter3 = $('.counter3'); // Second input
var $counter4 = $('.counter4'); // Third input
var $counter5 = $('.counter5'); // Ouput

$button9.click(function(){
  $counter5.val( parseInt($counter1.val()) * ((parseInt($counter4.val()) / 100) + 1) ** parseInt($counter3.val() )  ); // Calculates amount and loads it into .counter5

非常感谢有用的想法,谢谢。

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用 Number.toFixed

var $button9 = $('.increment-btn5'); // button to call the function below
var $counter1 = $('.counter1'); // First input
var $counter2 = $('.counter2'); // obsolete var at the moment
var $counter3 = $('.counter3'); // Second input
var $counter4 = $('.counter4'); // Third input
var $counter5 = $('.counter5'); // Ouput

$button9.click(function(){
  $counter5.val( 
    ( // begin calculation
      parseInt($counter1.val()) * 
      ((parseInt($counter4.val()) / 100) + 1) ** 
      parseInt($counter3.val() ) 
    ) // end calculation
    .toFixed(2) // round it to two decimals
  ); // pass it to counter5
});