首页 > 代码库 > js实现toFixed截取效果
js实现toFixed截取效果
Number.prototype.toFixed = function(fractionDigits) { var f = parseInt(fractionDigits) || 0; if( f < -20 || f > 100 ) { throw new RangeError("Precision of " + f + " fractional digits is out of range"); } var x = Number(this); if( isNaN(x) ) { return "NaN"; } var s = ""; if(x <= 0) { s = "-"; x = -x; } if( x >= Math.pow(10, 21) ) { return s + x.toString(); } var m; // 10. Let n be an integer for which the exact mathematical value of // n ÷ 10^f - x is as close to zero as possible. // If there are two such n, pick the larger n. n = Math.round(x * Math.pow(10, f) ); if( n == 0 ) { m = "0"; } else { // let m be the string consisting of the digits of the decimal representation of n (in order, with no leading zeroes). m = n.toString(); } if( f == 0 ) { return s + m; } var k = m.length; if(k <= f) { var z = Math.pow(10, f+1-k).toString().substring(1); m = z + m; k = f+1; } if(f > 0) { var a = m.substring(0, k-f); var b = m.substring(k-f); m = a + "." + b; } return s + m; };
转载--
js实现toFixed截取效果
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。