1

I'm using this one liner to generate a random 18 digit number :

Math.floor(100000000000000000 + Math.random() * 900000000000000000)

The problem is that it always contains one or more zeros at the end, and I don't understand why.

How can I generate a really random number that always contains 18 digits, and without a leading zero?

Dwix
  • 1,139
  • 3
  • 20
  • 45
  • 1
    Relevant: [What is JavaScript's highest integer value that a number can go to without losing precision?](https://stackoverflow.com/q/307179) – VLAZ Dec 23 '21 at 19:54
  • 1
    Check [this](https://stackoverflow.com/a/66993210/4543207) up. – Redu Dec 23 '21 at 20:12

3 Answers3

1

You have too many digits, you're running against the limit to precision in a javascript number.

Jason Goemaat
  • 28,692
  • 15
  • 86
  • 113
  • Oh ok thanks, I see. So is there a good solution to still generate a "unique enough" 18 digit number? without a leading zero – Dwix Dec 23 '21 at 19:58
  • 1
    @Dwix Generate two numbers and concatenate them as a string. – user229044 Dec 23 '21 at 19:59
  • 1
    Not storing it as a javascript 'number'. If you want to use it as such you need to find a [javascript library](https://mikemcl.github.io/bignumber.js/) (or write your own) that lets you use more precision. – Jason Goemaat Dec 23 '21 at 20:01
1

It looks like a Problem with the max number Range. You can hack it like this. And it is a better Random number.

Math.floor(10000000000000000 + Math.random() * 90000000000000000)+ "" + Math.floor(Math.random()* 100) 

But if you parse to int you have the same problem.

Denis Kohl
  • 739
  • 8
  • 13
  • I guess this is the way to go, but testing the first part alone `Math.floor(10000000000000000 + Math.random() * 90000000000000000)` it still mostly outputs a number ending with 0, why is that? – Dwix Dec 23 '21 at 20:05
  • Another thing, this solution sometimes outputs a 19 digit number instead of 18 though, where's the problem exactly? – Dwix Dec 23 '21 at 20:07
0

The solution for this so far is to generate two numbers (10 digits + 8 digits) & concatenate them as follow:

Math.floor(1000000000 + Math.random() * 9000000000) + "" + Math.floor(10000000 + Math.random() * 90000000)
Dwix
  • 1,139
  • 3
  • 20
  • 45