0

I made a script that generates a number between 1 and a googol (which is a number consisting of a 1 and a hundred zeros), but it can't display the numbers proberly. It makes numbers like "7.463677302002907e+99" and that's not what I want. I'm very new to Javascript, but I managed to make this. Here's the code:

<html>
<body>
<title>Random number between 1 an a googol-generator</title>

<p id="demo">Click the button to display a random number between 1 and a googol.</p>

<button onclick="myFunction()">Generate</button>

<script>
function myFunction()
{
var x=document.getElementById("demo")
x.innerHTML=Math.floor((Math.random()*10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)+1);
}
</script>

</body>
</html>
Community
  • 1
  • 1
Ragethe
  • 3
  • 5
  • 1
    Your generator does not generate really a random googol number. As floating numbers have limited decimal points Math.random() will not return a decimal number that consists of 100 digits. – RononDex Dec 18 '13 at 10:13
  • 2
    Isn't it more useful to generate a random number between 1 and 100, then generate that many random numbers and string them together? Or do you actually want to _use_ that number for anything, because then you will need some big integer library, see e.g. http://stackoverflow.com/questions/3072307/is-there-a-bignum-library-for-javascript – CompuChip Dec 18 '13 at 10:13
  • JavaScript's numbers use [double-precision floating-point](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) format, which has only 15 to 17 decimal digits of accuracy. If you did write that number out in full, most of it would be zeros. – Boann Dec 18 '13 at 10:20
  • For chrome, you can use toLocaleString to print the num, http://jsfiddle.net/rooseve/CKD52/, as you can see, random won't work for very large numbers, always many zeros.. – Andrew Dec 18 '13 at 10:47

1 Answers1

3

Javascript can't handle numbers that large. It can handle numbers with that magnitude, but not with that precision.

A number in Javascript is a floating point number, with about 15 digits precision. If you make a random number close to a googol, it would just be 15 digits at the start, then up to 85 zeroes at the end.

To create that large a number, you need to make several random numbers and put together the digits to form a large number. Example:

var s = '';
for (var i = 0; i < 10; i++) {
  s += Math.floor(Math.random() * 1e10);
}
while (s.length > 1 && s[0] == '0') s = s.substr(1);

Demo: http://jsfiddle.net/Guffa/YxJ3U/

Guffa
  • 687,336
  • 108
  • 737
  • 1,005