84636

MDN example (of Math.random()): could it be parseInt() instead of Math.floor()?

Question:

I was reading a JavaScript tutorial and searching for functions on MDN website when I stumbled across this example of Math.random():

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

While I understand that Math.floor chooses the biggest number and with that erases all numbers that have decimal values, I already learnt another function called parseInt() which just deletes all of the numbers after point. So, what's the difference between those two? Couldn't I just use

function getRandomInclusive(min, max) { return parseInt(Math.random() * (max - min + 1)) + min; }

instead? I got idea while writing this question that Math.floor() might write 5 when it's 4,5 and parseInt() would write 4, but it's not really important for random number generator as I understand (if you know any examples of when it would be important, please tell me!) So, there's still not much of a difference in this case?

Answer1:

parseInt parses a <em>string</em> into an integer, reading only digits at the beginning of that string. It is not appropriate to use to round a number to an integer. The number will be converted to a string first, sometimes with unexpected results:

var num = 1000000000000000000000; parseInt(num) // 1, because the string representation is 1e+21 <blockquote>

I got idea while writing this question that Math.floor() might write 5 when it's 4,5 and parseInt() would write 4

</blockquote>

You’re thinking of rounding to the nearest whole number, which is what Math.round does. Math.floor always rounds down.

Answer2:

The clear difference is that Math.floor is a function that works on numbers while parseInt is a function that takes a string. You don't want to use the latter here as we deal with random <em>numbers</em>.

If you are unsure about the rounding mode, compare Math.floor, Math.round and Math.ceil.

Answer3:

Here's an example where their behaviour differs drastically: negative numbers.

Math.floor(-2.5) -> -3 parseInt(-2.5) -> -2

The semantic difference pointed out in other answers, however, is probably more important. Even if it does work for your particular and specific use-case, it's best to pick the one with the correct semantics. (There are countless other ways to return a seemingly random integer from a function, you should pick the one that's the least likely to make your code hard to maintain.)

Recommend

  • Delphi 7 - How to delete an item from listview using its caption
  • How to determine differences in two lists of data
  • moving particles on face of imported *.obj in threejs
  • Why doesn't >= (greater than or equals) comparison work in Javascript?
  • getting java.lang.ClassCastException: class java.lang.String in running a simple MapReduce Program
  • Delphi XE6 - How to make user defined components image show up on the pallette
  • d3.js create stacked bar chart from values in object
  • How to make a user wait with Laravel
  • Convert Type Decimal to Hex (string) in .NET 3.5
  • zope_i18n_compile_mo_files doesn't work on a Zeo configuration
  • OOP Javascript - Is “get property” method necessary?
  • How to use an array of arrays with array_map(…) in PHP?
  • Highlight one bar in a series in highcharts?
  • Scrapy recursive link crawler
  • How to rebase a series of branches?
  • All Classes Conforming to Protocol Inherit Default Implementation
  • Android screen density dpi vs ppi
  • NetLogo BehaviorSpace - Measure runs using reporters
  • Javascript simulate pressing enter in input box
  • Ajax jQuery multiple calls at the same time - long wait for answer and not able to cancel
  • Is my CUDA kernel really runs on device or is being mistekenly executed by host in emulation?
  • How would I use PHP exceptions to define a redirect?
  • How to extract text from Word files using C#?
  • Perl system calls when running as another user using sudo
  • Deserializing XML into class C#
  • Statically linking a C++ library to a C# process using CLI or any other way
  • Build own AppleScript numerical error handling
  • Adding custom controls to a full screen movie
  • SVN: Merging two branches together
  • File upload with ng-file-upload throwing error
  • Buffer size for converting unsigned long to string
  • Load html files in TinyMce
  • Understanding cpu registers
  • Change div Background jquery
  • need help with bizarre java.net.HttpURLConnection behavior
  • How does Linux kernel interrupt the application?
  • Busy indicator not showing up in wpf window [duplicate]
  • Recursive/Hierarchical Query Using Postgres
  • Running Map reduces the dimensions of the matrices
  • Why do underscore prefixed variables exist?