Categories
JavaScript

JavaScript number functions and operations

Examples of mixing numbers and strings:

  • “1” + 2 + 4 will evaluate to 124 (looks like if the compiler finds a string the rest will also be considered a string)
  • 2 + 5 + “8” will evaluate to 78 (looks like after the compiler finds a string, then it behaves as one, but not before)
  • Number(“1”) + 2 + 4 will evaluate to 7
  • Instead of Number(), you can use +, like: +”1″ + 2 + 4

Parsing numbers:

  • parseInt(“3F”,16); Convert 3F hexadecimal to int. If you use 10 it will be decimal instead
  • parseInt will look for numbers at the beginning of the string, as oppose to Number, which will return NAN if a string is assigned to it
  • parseFloat parses floats

Other number functions:

  • isNaN(x)) Checks if x is a number. Returns true or false accordingly.
  • Math.round(number) Rounds the number to its closes integer.
  • Math.ceiling(x) Produce the ceiling of a number.
  • Math.floor(x) Produce the floor of a number
  • Useful function to produce random numbers from 1 to 9: Math.floor(Math.random()*10);
    This is a more generic representation of it:
    number = Math.floor(Math.random() * total_number_of_choices + first_possible_value)
    If you want to select
    a number between 2 and 10, then the code would look like this:
    var num = Math.floor(Math.random() * 9 + 2);