Pergunta

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>
Foi útil?

Solução

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/

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top