JSFiddle - React, Tailwind, and code Playground

by whelkaholism

JavaScript

Number.prototype.toFixedRounded = function(digits)
{
	var exp = Math.pow(10, digits);
  
	return Math.round(this * exp) / exp;
}

Number.prototype.toSignificant = function(digits, zeroissignificant)
{
    var outdigits = 0;
    var scale = Math.pow(10, digits - 1);
    var res = null;

    if (this < 1)
    {
    		var dp = digits - (zeroissignificant ? 1 : 0);
        
        console.log(this + ' < 1; DP=' + dp);
        
        res = this.toFixedRounded(dp);
    }
    else        
    {
        while (scale >= 0)
        {    
            if (this >= scale)
            {
                res = this.toFixedRounded(outdigits);
                break;
            }

            scale /= 10;

            if (outdigits < digits)
                outdigits++;
        }
    }

    return res;
};

var n = 0.585;
var m = 3.557634;
console.log(n.toSignificant(2));
console.log(m.toSignificant(2));