I need to write a function where i got one input parameter that can be a number from 1 to 9999. I need that output always be in a 4 digits format with a point between the numbers. For example, if the input is 1, the output must be 00,01. Input 157, ouput 01,57, and so on. Thanks
>Solution :
Consider utilizing padStart and slice:
const formatNum = num => {
if (!Number.isInteger(num)) throw "num must be an integer!";
if (num < 1 || num > 9999) throw "num must be between 1 and 9999 inclusive!";
const paddedNum = String(num).padStart(4, '0');
// TODO(@marcelo-teixeira-modesti): Add check to see if valid time as per train software requirements...
return `${paddedNum.slice(0, 2)},${paddedNum.slice(2)}`;
}
console.log(formatNum(1));
console.log(formatNum(157));
console.log(formatNum(2356));