Skip to content

Instantly share code, notes, and snippets.

@dsetzer
Created July 13, 2020 17:24
Show Gist options
  • Save dsetzer/4cf2db2d88e26fc6100384c1b8a10a69 to your computer and use it in GitHub Desktop.
Save dsetzer/4cf2db2d88e26fc6100384c1b8a10a69 to your computer and use it in GitHub Desktop.
decimal expansion function
// 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 (top, bottom, decLength) {
if (!isNumeric(top) || !isNumeric(bottom) || !isNumeric(decLength) || !bottom) {
return null;
}
var sign = ((top * bottom) != Math.abs(top * bottom)) ? "-" : "";
top = Math.abs(top);
bottom = Math.abs(bottom);
decLength = Math.abs(decLength);
var result = Math.floor(top / bottom),
remainder = top % bottom,
maxDecimal = 100,
i = Math.min(Math.max(0, decLength), maxDecimal) + 1;
if (1 < i) {
result += ".";
while (i--) {
top = remainder * 10;
remainder = top % bottom;
result += "" + Math.floor(top / bottom);
}
result = result.replace(/(\d)(\d)$/, function (match, a, b) {
return +b > 4 ? +a + 1 : a;
});
}
return sign + result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment