Nodejs Float Format toFixed(d)

Here you can find the source of toFixed(d)

Method Source Code

/*//from w  w  w  .  j  ava 2s . c  o m
 * To fix the number toFixed function issue
 */
Number.prototype.toFixed = function (d) {
    var s = this + "";
    if (!d) d = 0;
    if (s.indexOf(".") == -1) s += ".";
    s += new Array(d + 1).join("0");
    if (new RegExp("^(-|\\+)?(\\d+(\\.\\d{0," + (d + 1) + "})?)\\d*$").test(s)) {
        var s = "0" + RegExp.$2, pm = RegExp.$1, a = RegExp.$3.length, b = true;
        if (a == d + 2) {
            a = s.match(/\d/g);
            if (parseInt(a[a.length - 1]) > 4) {
                for (var i = a.length - 2; i >= 0; i--) {
                    a[i] = parseInt(a[i]) + 1;
                    if (a[i] == 10) {
                        a[i] = 0;
                        b = i != 1;
                    } else break;
                }
            }
            s = a.join("").replace(new RegExp("(\\d+)(\\d{" + d + "})\\d$"), "$1.$2");

        } if (b) s = s.substr(1);
        return (pm + s).replace(/\.$/, "");
    } return this + "";

};

Related

  1. formatFloat(num, pos)
    function formatFloat(num, pos) {
      var size = Math.pow(10, pos);
      return Math.round(num * size) / size;
    
  2. toFix(digits)
    Number.prototype.toFix=function(digits){
        var f=parseInt(digits),
            n=Number(this),
            s=n.toString();
        var p=s.split(".");
        if(p[1]&&p[1].length>f){
            p[1]=p[1].substring(0,f);
            n=Number(p.join("."));
        }else{
    ...
    
  3. toFixed(exponent)
    Number.prototype.toFixed = function(exponent) {
        if (exponent) {
            var result = (parseInt(this * Math.pow(10, exponent) + 0.5) / Math.pow(10, exponent)).toString();
            var count = 0;
            if (result.indexOf(".") > 0) {
                count = exponent - result.split(".")[1].length;
            } else {
                count = exponent;
                result += ".";
    ...
    
  4. toFixed10(precision)
    Number.prototype.toFixed10 = function(precision) {
        return Math.round10(this, -precision).toFixed(precision);
    
  5. toFixedBtoFixed ( precision )
    Number.prototype.toFixedB = function toFixed ( precision ) {
        var multiplier = Math.pow( 10, precision + 1 ),
            wholeNumber = Math.floor( this * multiplier );
        return (Math.round( wholeNumber / 10 ) * 10 / multiplier).toFixed(precision);
    
  6. toFixedDown(digits)
    Number.prototype.toFixedDown = function(digits) {
        var n = this - Math.pow(10, -digits)/2;
        n += n / Math.pow(2, 53); 
        return n.toFixed(digits);