Reputation: 390
Hey :) You can subtract as example 35% from a number with methods like this:
var valueInString = "2383";
var num = parseFloat(valueInString);
var val = num - (num * .35);
console.log(val);
But how is it possible to randomize the .35/0.35 part?
As example if I would try:
var randomREAL = require('randomize');
var randomARR = [30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75]
// randomREAL(randomARR) will generate a random number between 30 - 75 so that I can randomize my percentage value between 30% & 75%
var valueInString = "2383";
var num = parseFloat(valueInString);
var val = num - ( num * 0.randomREAL(randomARR) );
console.log(val);
I can´t use
0.randomREAL(randomARR)
or
.randomREAL(randomARR)
Also If I would build a string like
var test = randomREAL(randomARR)
0.test
it would not work.
Any ideas how to randomize the percentage value ?
Upvotes: 0
Views: 128
Reputation: 889
To easily get random numbers between an interval you can use this very simple function from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
Upvotes: 1
Reputation: 138557
+("0."+randomARR[ Math.floor( randomARR.length * Math.random() ) ])
As youve pointed out
Also If I would build a string like
var test = randomREAL(randomARR) 0.test
it would not work.
Because 0.
is not a string. You want string concatenation e.g.:
"0."+35
And then you need to parse it back into a number, which can be done with the unary plus operator
:
+("0."+35)
Additionally if the number is always two digits, you can also use /100
...
Hint: To get a random integer between 30 and 75 is as easy as:
30 + Math.floor( Math.random() * ( 75 - 30 ))
Upvotes: 2