Sunday, December 13, 2015

Enforcing a given number of digits in a numeric value in Javascript

Javascript does not a built-in functionality like C#'s .ToString("0000").

To accomplish the same I came up with the following:

function setNumericFormat(value, numOfDigits, paddingChar) {
var length = value.toString().length;
if (length < numOfDigits) {
var prefix = "";
for (var i = 1; i <= numOfDigits - length; i++) {
prefix += paddingChar;
}
return prefix + value.toString();
}
return value.toString();
}

Resembles a LeftPad function...

No comments:

Post a Comment