How to parse float with two decimal places in javascript?

前端 未结 16 1710
春和景丽
春和景丽 2020-11-27 08:55

I have the following code. I would like to have it such that if price_result equals an integer, let\'s say 10, then I would like to add two decimal places. So 10 would be 10

16条回答
  •  迷失自我
    2020-11-27 09:38

    When you use toFixed, it always returns the value as a string. This sometimes complicates the code. To avoid that, you can make an alternative method for Number.

    Number.prototype.round = function(p) {
      p = p || 10;
      return parseFloat( this.toFixed(p) );
    };
    

    and use:

    var n = 22 / 7; // 3.142857142857143
    n.round(3); // 3.143
    

    or simply:

    (22/7).round(3); // 3.143
    

提交回复
热议问题