2

I want to get a random double number (for example 4.58) and put its digits to three variables - 4 to the first variable, 5 to the second variable and 8 to the third variable.

lukelazarovic
  • 1,510
  • 11
  • 19

3 Answers3

2

Not sure why you need this to be a floating-point number. Just create a three-digit number, convert it to a string, and split it into an array.

var numArr = (Math.floor(Math.random() * 900) + 100).toString().split('');

You can get at the numbers using the normal array method: numArr[0] etc.

To convert it to number, add a period in the first array position and then join it back to together:

numArr.splice(1, 0, '.');
var number = numArr.join('');

DEMO

Alternatively, see this SO question on how to create random floating-point numbers.

Community
  • 1
  • 1
Andy
  • 61,948
  • 13
  • 68
  • 95
1

You could do something like this:

var number = 4.26; // Your generated double number
output = []; // Array to store each digit
sNumber = number.toString(); // Convert the double to a string so we can split it

for (var i = 0, len = sNumber.length; i < len; i += 1) 
{
    output.push(+sNumber.charAt(i));
}

console.log(output);

The output will be:

4, 2, 6

All numbers in JavaScript are doubles: that is, they are stored as 64-bit IEEE-754 doubles.

That is, the goal is not to get a "double": the goal is to get the string reprsentation of a number formatted as "YYY.XX". For that, consider Number.toFixed, for instance:

(100).toFixed(2)

The result is the string (not a "double"!) "100.00". The parenthesis are required to avoid a grammar ambiguity in this case (it could also have been written as 100.0.toFixed or 100..toFixed), but would not be required if 100 was in a variable.

AnonDCX
  • 2,501
  • 2
  • 17
  • 25
1

Use this. I use .replace(/[.]/g,"") for removing ".".

http://jsfiddle.net/sherali/coyv3erf/2/

var randomNumber = Math.floor(Math.random() * 900) + 100;
numArr= randomNumber.toString().replace(/[.]/g,"").split("")
var number = numArr.join("");

console.log(numArr, number); // ["8", "4", "5"]  845
Sherali Turdiyev
  • 1,745
  • 16
  • 29
  • thanks :) the reason behind this question , is , i want to make an exercise for children to compute the meter in unites , so if the child press "new problem" a random float number displayed in text , and if he press "solution button" i want to take the numbers of the float- number to show him the solution – Oraib Abo Rob Sep 06 '15 at 18:11
  • @Oraib Abo Rob. I have edited my answer. There are three variables(randomNumber, numArr, number) for using – Sherali Turdiyev Sep 06 '15 at 19:50
  • Accept correct answer, if find you answer. Otherwise, explain it what you wish – Sherali Turdiyev Sep 08 '15 at 17:06