Number.prototype.toFixed was giving me too many problems, so I just rewrote it.
There’s the source.
/**
@author Larry Battle Contact Me
@date Mar 30, 2012
@purpose Provide the fix for Number.prototype.toFixed() function.
@info source at http://bateru.com/news/2012/03/reimplementation-of-number-prototype-tofixed
*/
Number.prototype.toFixed_fix = function (precision) {
var num = this.toString(), zeros = '00000000000000000000', newNum, decLength, factor;
if (0 > precision || precision > 20) {
throw new RangeError("toFixed() digits argument must be between 0 and 20");
}
if (Math.abs(num) === Infinity || Math.abs(num) >= 1e21) {
return num;
}
precision = parseInt(precision, 10) || 0;
newNum = num = isNaN(parseInt(num, 10)) ? '0' : num;
if (/\./.test(num)) {
decLength = num.split('.')[1].length;
if (decLength < precision) {
newNum += zeros.substring(0, precision - decLength);
} else {
factor = Math.pow(10, precision);
newNum = Math.round(num * factor) / factor;
}
} else {
if (precision) {
newNum += '.' + zeros.substring(0, precision);
}
}
return newNum;
};
Test cases here
Want to learn more about Javascript?
Checkout this 'Professional JavaScript for Web Developers'.
What REALLY is Data Science? Told by a Data Scientist - By Joma Tech
Writing perfect code is a challenging process. That's where code reviews come in to help…
"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"
"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"
My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…
View Comments
wrong testcase (13.3).toFixed(19) should be "13.3000000000000007105"
You're missing the point.
Without the fix for `Number.prototype.toFix`, `(13.3).toFixed(19) === "13.3000000000000007105"`.
That is inacurate since the value of 13.3 was supplied and not 13.3000000000000007105, which converts to 13.3 by the way.
For more information, refer to the links below
http://stackoverflow.com/questions/588004/is-javascripts-math-broken
http://stackoverflow.com/questions/11339431/javascript-floating-point-curiosity
and???? seems, it is you are missing the point, 13.3 is stored as double, and "13.3000000000000007105" is CLOSER to the stored double value, than 13.3000000000000000000, browsers implementation (FF, Chrome, IE9, Opera) is correct, your implementation is wrong