1

I've got a little function, which allows to receive some integer which must be percentage value (0-100), and rolls some chance to understand if it's currently true or not (roll):

function RollV (value) {
        var rollvalue = Math.floor((Math.random() * 100) + 1),
        result = true;
        if (value >= rollvalue) {
            result = true;
        } else {
            result = false;
        }
        return result;
    }

From what I understand, this func will not return true with float value, because random rollvalue couldn't be float, like if I want to use 0.001% chance, this will not be passed as true, is there any ways to make math random with float values?

JSFiddle: http://jsfiddle.net/7nbv2nrd/

4
  • Math.random() returns a random number greater than or equal to zero and less than 1. The code you've got uses that to pick a random integer, but there's nothing inherent about Math.random() that limits you to integers.
    – Pointy
    Sep 22, 2014 at 13:25
  • 1
    Also please just return value >= rollvalue
    – mplungjan
    Sep 22, 2014 at 13:29
  • your result is a global variable, add var before it. Sep 22, 2014 at 13:32
  • What mplungjan said, or even return value >= Math.floor((Math.random() * 100) + 1). It's really not a complicated enough calculation to need an intermediate variable, unless you need to log it.
    – nnnnnn
    Sep 22, 2014 at 13:35

2 Answers 2

2

You can use following code:

 (Math.random() * (upper_limit - lower_limit) + lower_limit).toFixed(3)

Update

As @Pointy said, this will return string and if you want it to be float you can use parseFloat(value) or .toFixed()

Edit

Math.random() result is float by default and if you don't want to set a limit ( let's say your ok with values from 0 to 1 ), than remove Math.floor from your code

3
  • 2
    It should be noted that this code will return a string, not a number.
    – Pointy
    Sep 22, 2014 at 13:24
  • 1
    You don't have to use .parseFloat(); you can simply skip the call to .toFixed().
    – Pointy
    Sep 22, 2014 at 13:25
  • There's not really any need to use toFixed(), because the random number doesn't ever get displayed, it just gets compared to whatever is passed into the value argument. (I realise the demo fiddle does display it, but that seems like a testing thing, not a real requirement of the problem as described.)
    – nnnnnn
    Sep 22, 2014 at 13:42
1

This works for me.

FIDDLE

function RollV(value) {
    var rollvalue = Math.random();
    $('.result').text(rollvalue);
    return value >= rollvalue;
}

console.log(0.01,RollV(0.01));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.