0

So, I'm wondering what I'm doing wrong here? It's giving me numbers like 3. (I'm passing the variable a as "7-10")

function getDmg(a, y) {
    var s = Math.floor((Math.random() * (a.split('-')[1])) + (a.split('-')[0])); 
    if(y == true) {
        console.log('You dealt ' + s + ' damage.');
    } else {
        console.log('You took ' + s + ' damage.');
    }
    return s; // Giving numbers like 3...?
}
Alex Szabo
  • 3,274
  • 2
  • 18
  • 30
Anthemius
  • 29
  • 5
  • 3
    The split function is a string function. You should convert the result of the split to a number with `parseInt()` or `parseFloat()` before you attempt math on it. – Scott Marcus Nov 06 '16 at 19:53
  • Just an alternate approach [JSFiddle](https://jsfiddle.net/uc87xbc8/) – Rajesh Nov 07 '16 at 08:33

2 Answers2

0

Math.random returns random values between 0 (inclusive) and 1 (exclusive). To get a number from 7 to 10, you'll need to specify the max value, subtract the min and then ADD your min value to the result:

This adjusted code returns random damages in your range. Remember: if you do want to possibly get a max of 10, you need to pass 11 as the upper value for Math.random because the upper value is exclusive:

function getDmg(a, y) {
    var min = parseInt(a.split('-')[0],10);
    var max = parseInt(a.split('-')[1],10);
  
    var s = Math.floor(Math.random() * (max - min) + min); 
    if(y == true) {
        console.log('You dealt ' + s + ' damage.');
    } else {
        console.log('You took ' + s + ' damage.');
    }
    return s; // Giving numbers like 3...?
}

getDmg("7-11", true);
getDmg("7-11", false);

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random for more details on Math.random()

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • I was passing 7-10, hoping for a number in between 7 and 10. But it was giving me numbers waaayy off than what I expected. – Anthemius Nov 06 '16 at 20:15
  • `parseInt` extracts the number at the beginning of a string. It's not exactly string to number coercion. I suggest against using it. – Oriol Nov 06 '16 at 20:26
  • @Oriol True, but if the input can be regulated (for example `input type=number` or `input type=range`, then it's a non-issue. – Scott Marcus Nov 06 '16 at 20:27
0
function getDmg(range, dealt) {
    var damageRange = range.split("-");

    //This will have to be made more "error-proof"
    var min = Number(damageRange[0]);
    var max = Number(damageRange[1]);

    //This formula will take the min and max into account
    var calculatedDamage = Math.floor(Math.random() * (max - min + 1)) + min;

    console.log((dealt ? "You dealt " : "You took ") + calculatedDamage + " damage.");
    return calculatedDamage;

}

Good replies can be found @ Generate random number between two numbers in JavaScript

Community
  • 1
  • 1
Alex Szabo
  • 3,274
  • 2
  • 18
  • 30