Skip to content

Instantly share code, notes, and snippets.

@hugabor
Last active October 11, 2016 19:02
Show Gist options
  • Select an option

  • Save hugabor/ad34d2ab39009cf761a9a77d9c63f092 to your computer and use it in GitHub Desktop.

Select an option

Save hugabor/ad34d2ab39009cf761a9a77d9c63f092 to your computer and use it in GitHub Desktop.
Basic, often-used functions for stringifying positive numbers (in JavaScript)
let fixLength = function(num, length) {
let numStr = "" + num;
if (parseInt(numStr, 10) < 0) return fixLength(0, length);
while (numStr.length < length) {
numStr = "0" + numStr;
}
return numStr;
};
let fix = function(num, decimalPlaces) {
let numStr = "" + num;
if (decimalPlaces > 0) {
numStr += ".";
for (let i = 1; i < decimalPlaces; ++i) {
numStr += Math.floor(num * Math.pow(10, i)) % 10;
}
}
return numStr;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment