One thing that is common knowledge about JavaScript and other languages is that floating point numbers are not always stored the way you think. Also doing math with these numbers is even more iffy. One thing I recently wanted to do was effectively the opposite of `parseInt()`

. In other words, I just wanted the fractional part of the passed number to be returned. Thusly the following function was born:

/** * @license Copyright 2014 - Chris West - MIT Licensed */ (function(RGX) { frac = function(num) { return +(+num).toExponential().replace(RGX, function(m, neg, num, dot, offset) { var zeroes = Array(Math.abs(offset) + 2).join('0'); num = (zeroes + num + (dot ? '' : '.') + zeroes).split('.'); return +(neg + '.' + num.join('').slice(+offset + num[0].length)); }); }; })(/(-?)(\d+(\.?)\d*)e(.+)/);

I really got the idea from the first programming language I ever used: that of the Casio graphing calculators. The following are example calls and results for the function:

var a = frac(1.234); // 0.234 var b = frac(56789e-3); // 0.789 var c = frac(12345678); // 0 var d = frac(-34.5697); // -0.5697 var e = frac('-.9'); // -0.9 var f = frac(null); // 0 var g = frac(undefined); // NaN var h = frac('sdfa'); // NaN

Personally I thought it was strange that this function isn’t natively provided in most languages but there are some alternatives. One that works in some languages but not in JavaScript (nor in Python interestingly enough) is the following:

a = 34.5697; fracPart = a % 1; alert(fracPart); // 0.5696999999999974

Another alternative method that seems like it should work but doesn’t in JavaScript is as follows:

a = 34.5697; fracPart = a - parseInt(a); alert(fracPart); // 0.5696999999999974

For this reason, if you have a need to pull the decimal portion of a number out, feel free to use the `frac`

function defined at the beginning of this post. 😎