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:

``````
/**
*/
(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.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;
``````

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

``````
a = 34.5697;
fracPart = a - parseInt(a);
``````

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. 😎 #### ildar · April 4, 2014 at 2:05 AM

``` a = 34.5697; fracPart = a % 1; alert(fracPart); ```

This is absolutely correct solution in JS. Check, for example with the result of `34.5697 - 34`. #### Alex Nash · July 18, 2019 at 12:08 PM

There is a simpler solution: just replace the whole part using `Math.trunc()`.
I’ve published typescript implementation in a public gist:
https://gist.github.com/Nachasic/21259aae50d0c798b5c28edb3547b318