algorithm - Convert number to list of three digits in Javascript -


this question has answer here:

i'm getting large numbers input , want display them small space every step of thousand (every 3 digits). i'm looking array of max. 3 digits output.

examples:

input: 10       output: [10] input: 1234     output: [1, 234] input: 24521280 output: [23, 521, 280] 

it not matter if output array contains strings or numbers.

what elegant (comprehensive / short) solution in javascript es6?


i wrote 2 working solutions, feel overly complicated or i'm missing something:

solution 1)

function numbertothreedigitarray(number) {   if (number / 1000 < 1) return [number];    return [     ...numbertothreedigitarray(math.floor(number / 1000)),     number % 1000   ]; } 

solution 2)

function numbertothreedigitarray(number) {   return number.tostring().split('').reverse().map((char, i) => {     return !== 0 && % 3 === 0       ? ' ' + char       : char;   }).join('').split('').reverse().join('').split(' '); } 

number.tolocalestring().split(',').map(num => +num) should you.

see tolocalestring mdn docs.

example:

const arr = (24521280).tolocalestring().split(',').map(num => +num)  // [24, 521, 280]  // or  function getnumber(n) {   return n.tolocalestring().split(',').map(num => +num) } 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -