Search code examples
javascriptnumbersdigitsroman-numerals

How can I break numbers into their digit values?


As part of a Roman numerals converter algorithm, I would like to break a given number into their digit values. What I precisely want to do is as follows:

1984 = 1000+900+80+4

It would be better to let you know where I will use the outcome. I will push the result in an array and match with their Roman numeral counterpart, e.g. 1000 = M, 900 = CM, 80 = LXXX, 4 = IV.

1984 = MCMLXXXIV

What kind of function is needed to produce the expected output?


Solution

  • I tweaked it into this one-liner:

    Array.from((1984).toString()).reverse().map((d, i) => d * 10 ** i)
    

    This will give you the parts in reverse (least significant digit first); depending on your need you may want to add another .reverse() at the end.