
Today’s Code of the Day is about decimal expansion, which is just division.
So you might be asking yourself, “if decimal expansion is divsion. Then why not use a/b?”.
Well the problem is that Javascript has a ton of problems when dealing with floating point operations because of the way they are stored.
Examples:
var a = 1/3; a.toString() // returns "0.3333333333333333" a.toFixed(25); // returns "0.3333333333333333148296163" 0.1 + 0.2; // returns 0.30000000000000004
Source for decimalExpansion()
// borrowed from jQuery 1.7.2 var isNumeric = function(val){ return !isNaN(parseFloat(val)) && isFinite(val); }; /** * @author Larry Battle <http://bateru.com/news/contact-me> * @date May 16, 2012 * @license MIT and GPLv3 */ //decimalExpansion returns a string representation of a divided by b to a fixed length. // All the paramaters must be whole numbers. // Example: decimalExpansion( 1, 3, 3 ) === "0.333" var decimalExpansion = function( a, b, decLength){ if( !isNumeric(a) || !isNumeric(b) || !a || !isNumeric(decLength) ){ return null; } var arr = [], tmp="", val, aLen = a.toString().length, i = 0, maxDecimal = 100; decLength = Math.min( Math.max( 0, decLength||0 ), maxDecimal) + aLen; while( i < decLength ){ if( i===aLen){ arr.push('.'); } tmp += a.toString().charAt(i) || "0"; val = Math.floor( (+tmp)/+b ); arr.push( val ); tmp %= b; i++; } if (tmp > 4) { arr[arr.length - 1]++; } return arr.join('').replace( /^(-)?0+(?=\d)/, ''); };
Test cases:
Demo:
Here are excellent links over the topic.
Wolfram MathWorld: Decimal Expansion
Wikipedia.org: Fraction (mathematics)
Oracle: What Every Computer Scientist Should Know About Floating-Point Arithmetic

Recent Comments