Javascript toFixed function

前端 未结 6 1744
春和景丽
春和景丽 2020-12-30 04:51

The expected result of:

(1.175).toFixed(2) = 1.18 and
(5.175).toFixed(2) = 5.18

But in JS showing:

6条回答
  •  猫巷女王i
    2020-12-30 05:35

    You could always try using round, instead of toFixed.

    Math.round(5.175*100)/100

    You could even try putting it in some prototype method if you want.

    Created a jsBin that implements a simple prototype on Number.

    Number.prototype.toFixed = function(decimals) {
     return Math.round(this * Math.pow(10, decimals)) / (Math.pow(10, decimals)); 
    };
    

提交回复
热议问题