phpjs
Version:
79 lines (64 loc) • 2.2 kB
Markdown
layout: page
title: "JavaScript fmod function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/fmod:404
- /functions/view/fmod
- /functions/view/404
- /functions/fmod:404
- /functions/404
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's fmod
{% codeblock math/fmod.js lang:js https://raw.github.com/kvz/phpjs/master/functions/math/fmod.js raw on github %}
function fmod (x, y) {
// From: http://phpjs.org/functions
// + original by: Onno Marsman
// + input by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: fmod(5.7, 1.3);
// * returns 1: 0.5
var tmp, tmp2, p = 0,
pY = 0,
l = 0.0,
l2 = 0.0;
tmp = x.toExponential().match(/^.\.?(.*)e(.+)$/);
p = parseInt(tmp[2], 10) - (tmp[1] + '').length;
tmp = y.toExponential().match(/^.\.?(.*)e(.+)$/);
pY = parseInt(tmp[2], 10) - (tmp[1] + '').length;
if (pY > p) {
p = pY;
}
tmp2 = (x % y);
if (p < -100 || p > 20) {
// toFixed will give an out of bound error so we fix it like this:
l = Math.round(Math.log(tmp2) / Math.log(10));
l2 = Math.pow(10, l);
return (tmp2 / l2).toFixed(l - p) * l2;
} else {
return parseFloat(tmp2.toFixed(-p));
}
}
{% endcodeblock %}
- [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/math/fmod.js)
Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are
the closest match to this hashtable-like data structure.
Please also note that php.js offers community built functions and goes by the
[McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online
functions that are far from perfect, in the hopes to spark better contributions.
Do you have one? Then please just:
- [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/math/fmod.js)
### Example 1
This code
{% codeblock lang:js example %}
fmod(5.7, 1.3);
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
0.5
{% endcodeblock %}
### Other PHP functions in the math extension
{% render_partial _includes/custom/math.html %}