0

In Python, I can convert a number to a string in a custom format. For example - hexadecimal, minimum width 5, with leading zeroes:

>>> i = 4660
>>> f'{i:05x}'
'01234'

How do I do the same in JavaScript? Is there a better way than the following?

> var i = 4660
> ('00000' + i.toString(16)).substr(-5)
'01234'

Edit: So, it seems the solution in this specific example is i.toString(16).padStart(5, '0'). In general, though, is there no sprintf-like function in JavaScript?

user200783
  • 13,722
  • 12
  • 69
  • 135
  • 1
    There is no sprintf like function. You can roll your own very easily and there are some number based proposals to the tc39 to be more assistive in converting base numbers - however, padding 0s isn't specifically being addressed. This probably has to do with prior versions of JavaScript using leading 0's as a flag to interpret differently. – zfrisch Jul 15 '19 at 19:31
  • @zfrisch - Thank you for answering my question. – user200783 Jul 15 '19 at 20:05

0 Answers0