How to format numbers by prepending 0 to single-digit numbers? 1

How to format numbers by prepending 0 to single-digit numbers?

[7, 7.5, -7.2345].forEach(myNumber => {
  let formattedNumber = myNumber.toLocaleString('en-US', {
    minimumIntegerDigits: 2,
    useGrouping: false
  })
  console.log(
    'Input:    ' + myNumber + '\n' +
    'Output:   ' + formattedNumber
  )
})
 Run code snippetHide results

Here is what the above code is Doing:
1. We’re using the toLocaleString() method to format the number.
2. We’re passing in the locale ‘en-US’ to format the number in the US format.
3. We’re passing in an options object with the following properties:
minimumIntegerDigits: 2 – This ensures that the number has at least 2 digits.
useGrouping: false – This ensures that the number is not formatted with commas.
4. We’re logging the input and output to the console.

Similar Posts