Categories: Frontend Tech

Code of the day: Fix for Number.prototype.toFixed

In javascript, Number.prototype.toFixed has problems rounding.
Here’s the fix and some test cases.

Number.prototype.toFixed = (function () {
	var oldToFixed = Number.prototype.toFixed;
	return function (precision) {
		var value = this.toString(), power = Math.pow(10, precision || 0);
		return oldToFixed.call((Math.round(value * power) / power), precision);
	};
}());


Here’s a simple test.

// Programmer: Larry Battle
// Link: http://bateru.com/news/2012/03/code-of-the-day-fix-for-number-prototype-tofixed
(function (root) {
	"use strict";
	var log = function( str ){
		root.document.body.innerHTML += "log: " + str + "
"; }, assert = function (a, b ) { var message = a + ' !== ' + b; message += ( a === b ) ? "=> true" : "=> false"; log( message ); }; assert((0.595).toFixed(2), "0.59"); assert((0.9).toFixed(0), "1"); Number.prototype.toFixed = (function () { var oldToFixed = Number.prototype.toFixed; return function (precision) { var value = this.toString(), power = Math.pow(10, precision || 0); return oldToFixed.call((Math.round(value * power) / power), precision); }; } ()); log("Applying the toFixed fix."); assert((0.595).toFixed(2), "0.60"); assert((0.9).toFixed(0), "1"); }(this));

Demo: Link

Update!
Improved code here

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

Share
Published by
Larry Battle

Recent Posts

What really is Data Science? Told by a Data Scientist

What REALLY is Data Science? Told by a Data Scientist - By Joma Tech

7 years ago

Video: How Water Towers Work

How Water Towers Work - Practical Engineering

7 years ago

Dev Tip: Simple tips to improve code reviews

Writing perfect code is a challenging process. That's where code reviews come in to help…

7 years ago

Video: How AI will change the 3d industry

"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"

7 years ago

Best Software Presentation for 2018

"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"

7 years ago

Dev Video: A Few Linux Shell Tips

My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…

7 years ago