2

I'm using this function to generate random int values :

var r = function(min, max){
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

It works perfectly but makes me wonder ... why there is no randomInt and randomFloat in javascript?

rafaelcastrocouto
  • 11,781
  • 3
  • 38
  • 63
  • Because javascript is far from being perfect. – gdoron Sep 11 '13 at 17:24
  • replace `return Math.floor(Math.random() * (max - min + 1)) + min` with `return Math.ceil(Math.random() * (max - min )) + min` – Math chiller Sep 11 '13 at 17:25
  • 5
    There is no good answer to *why*, that's just the way the language is. As you know, it provides a random method, which can be used to generate random integers as you did. – bfavaretto Sep 11 '13 at 17:27
  • @bfavaretto then the answer is, there is no good reason javascript just sucks, because it only has `number`s. – Math chiller Sep 11 '13 at 17:30
  • 1
    @tryingToGetProgrammingStraight I have to disagree with that. If js sucks (and I don't think it does), it wouldn't be for the lack of an Integer type or a randomInt method. – bfavaretto Sep 11 '13 at 17:33
  • @bfavaretto yes we do all know it has the bad parts, (scopes) and the fact that everything is a `number`, also has some downsides. – Math chiller Sep 11 '13 at 17:36
  • 1
    @tryingToGetProgrammingStraight, you think JavaScript's functional scope is a *bad* part of the language? I quite like scope in JS. – zzzzBov Sep 11 '13 at 17:48
  • @zzzzBov no i lied i dont `think JavaScript's functional scope is a bad part of the language` hehe i tricked you. – Math chiller Sep 11 '13 at 17:55

2 Answers2

13

JavaScript has a Number type which is a 64-bit float; there is no Integer type per se. Math.random by itself gives you a random Number, which is already a 64-bit float. I don't see why there couldn't be a Math.randomInt (internally it could either truncate, floor, or ceil the value). There is no good answer as to why the language doesn't have it; you would have to ask Brendan Eich. However, you can emulate what you want using Math.ceil or Math.floor. This will give you back a whole number, which isn't really an Integer typewise, but is still a Number type.

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
2

Because Javascript doesn't have those types. Pure javascript only has a generic number type.

More info on Javascript types may be found here and here.

You may also want to look into this question: Integers in JavaScript

The marked answer says, and I quote:

There are really only a few data types in Javascript: Objects, numbers, and strings. As you read, JS numbers are all 64-bit floats. There are no ints.

Community
  • 1
  • 1
Geeky Guy
  • 9,229
  • 4
  • 42
  • 62