Formatting a number with exactly two decimals in JavaScript

后端 未结 30 2294
广开言路
广开言路 2020-11-21 06:29

I have this line of code which rounds my numbers to two decimal places. But I get numbers like this: 10.8, 2.4, etc. These are not my idea of two decimal places so how I can

30条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 06:49

    Put the following in some global scope:

    Number.prototype.getDecimals = function ( decDigCount ) {
       return this.toFixed(decDigCount);
    }
    

    and then try:

    var a = 56.23232323;
    a.getDecimals(2); // will return 56.23
    

    Update

    Note that toFixed() can only work for the number of decimals between 0-20 i.e. a.getDecimals(25) may generate a javascript error, so to accomodate that you may add some additional check i.e.

    Number.prototype.getDecimals = function ( decDigCount ) {
       return ( decDigCount > 20 ) ? this : this.toFixed(decDigCount);
    }
    

提交回复
热议问题