Search code examples
javascriptarraysdecimal

How to generate a number range with N decimal places


I need to generate a large array of numbers ranging from 0.00 to say 10000000.00 i.e 0.01 0.02 0.03 ... 1.51 1.52 1.583 ... etc

After looking around, I tried this answer which works fine for integers but however not working for decimals


Solution

  • In javascript, you can try:

    let numbers = [];
    for (let i = 0; i <= 10000000; i += 0.01) {
        numbers.push(parseFloat(i.toFixed(2))); //you can use toFixed(3) too if you want
    }
    

    Please note that creating a very large array like this will consume a lot of memory and may lead to performance issue.