You are confusing strings and numbers. Numbers have a "canonical form" that you see, for example, when you print or log them; however, numbers can have many different formats that all get parsed or converted into the same number.
For example, consider the following number literals which all represent the same number (3):
[3, 3.0, 03, +3e0].map(Number); // => [3, 3, 3, 3]
Moreover, parsing those literals from string values also results in the same number:
['3', '3.0', '03', '+3e0'].map(Number); // => [3, 3, 3, 3]
What this means is that if you want a number to appear differently than its canonical form then you must "format" it. In your example, it sounds like you're already getting a formatted number ("03"
) so perhaps you just want to validate the string to confirm that it is an acceptable number and use the input string as-is, or a formatted version of the validated number. For example:
function validateNumber(s) {
// Parse the input string as a number.
var n = Number(s);
// Validate the number to make sure it's ok based on your business logic.
if (!Number.isInteger(n)) {
throw new Error('invalid integer: ' + s);
}
// Format it to look like we want.
var formatted = String(s);
return ((formatted.length < 2) ? '0' : '') + formatted;
}
validateNumber(3); // => "03"
validateNumber("03"); // => "03"
validateNumber(20); // => "20"