JavaScript: Working with numbers

JavaScript: Working with numbers

Deeper dive into working with numbers in JavaScript.

ยท

10 min read

In other languages like C or Java, you have to be specific as to what kind of number you wish to store in a variable. You'd need to explicitly tell the compiler if the variable will store a floating point value (a number with a decimal point), or an integer (with no decimal points). Whereas in JavaScript, you do not have to worry about that.

You do not even need to tell JavaScript what kind of value you are storing beforehand. JavaScript just detects it automatically and knows how to handle operations with it.

๐Ÿ’ก
Even though there are limitations and somewhat inaccuracies that may occur in your dealings with numbers in JavaScript, this is not often an issue in small / middle-scale projects. You will be more comfortable dealing with them when you are already comfortable writing JavaScript programs so we'll leave those details out.

As we have previously established, all numbers in JavaScript are of the type number (not Number - recall that JavaScript is case-sensitive).

typeof 1 // 'number'
typeof 2.5 // 'number'
๐Ÿ’ก
There is a function used to create 'number objects' called Number. When we discuss constructor functions sometime in the future, we'll learn about the Number constructor function.

NUMBER METHODS

Recall that we have established a common knowledge that the properties and behaviour associated with variables differ based on the value they hold. When a variable holds a number value, there are some methods available (behaviours) to it.

To access the properties and methods associated with a particular variable, simply use the dot (.) notation i.e., write the variable name [and without any whitespace], type a dot next to it like this;

Notice that in the image above, immediately after the dot (.) notation, we get a list of available properties and methods attached to the age variable.

You can simply choose to type out the method you wish to use, followed by brackets (without space), or even click any from the dropdown and then add brackets to it.

If you are using a method, you'll need the brackets to invoke/call it, but if it is just a property, you won't be needing any brackets.

๐Ÿ’ก
A method is a function that lives inside an object. And to call/invoke functions, recall that we need to attach brackets to its name. When you call a method, the object to the left of the dot (.) operator is known as the caller. For example; In this statement age.toFixed(), the caller here is the variable age

For the rest of this article, let's examine some of the methods available to a number variable, and how to use them in our code.

Fortunately or unfortunately, there isn't any immediately obvious reason for these functions or the job they do, but I will attempt to explain a few of them that might come in handy in your journey as a developer;

๐Ÿ’ก
In the methods explained below, when you see a text enclosed in an square bracket inside the normal bracket notation, just know that that text represents an optional argument. this means you can decide whether to pass a value for that parameter during the function call or not.
  • toExponential([fractionDigits]): The toExponential method is used to convert a number to its exponential notation (if you are not a math lover, you might want to look up the meaning of exponent online - I'm avoiding going into maths here).

    Observe the code below;

      let age = 20;
    
      console.log(age.toExponential()); // 2e+1
    

    If you run the code above in your editor/browser console, you'll get the result; 2e+1 which is the exponential notation of 20 in JavaScript. In very simple terms, it means; 2, times 10 raised to the power of 1.

    ๐Ÿ’ก
    Try this: console.log(2e+1) and see the result. Also, run this code console.log(typeof 2e+1).

    You might find this function useful if you are writing a maths app though ๐Ÿ‘

  • toFixed([fractionDigits]): The toFixed method is used to convert a number to a fixed value i.e., you can specify if you want decimal points added to a number, and how many values to keep after the decimal point is inserted. When invoking the toFixed method, you can either provide an argument to represent the fraction digits (number of decimals you want the result to have) or not*.*

      let count = 2.34;
    
      console.log(count.toFixed()); // '2'
      console.log(count.toFixed(1)); // '2.3'
    

    If you do not provide an argument (a number which represents the desired fraction digits), it would remove all digits after the decimal point from the caller, convert the result to a string and return it. but if you do pass in an argument, the decimals would be adjusted accordingly, converted to a string and returned.

    If there is no decimal point in the number on which it was called and the required argument is not passed into the toFixed function, the caller itself is converted to a string and returned.

      // Write a function to convert any number passed 
      // into it to a whole number then return it.
      function convertToWholeNumber (num) {
          return num.toFixed()
      }
    
      console.log(convertToWholeNumber(2.34)); // 2
      console.log(convertToWholeNumber(2)); //2
    
  • toString([radix]): This method is used to convert a number to its string representation using the specified radix (base). If the radix is provided, the caller is converted to its corresponding value in the specified radix, or else, it is returned in base 10.

    ๐Ÿ’ก
    Radix means base. So both words can be used interchangeably here.

    The accepted bases/radix for this function ranges from 2 - 36 (whole numbers) and it returns a string representation of the result.

      // This code will convert 10 to it's equivalent in base 2 and return
      // the result in string format.
      let value = 10;
    
      console.log(value.toString(2)); // 1010
    

    If no radix is provided, the caller is simply converted to a string and returned (internally what happened is that the caller is converted to its base 10 equivalent and returned in string format).

    ๐Ÿ’ก
    Try this: Excercise your mind by using this method on different values (both string and number) then observe how it behaves. If you find that you are getting confused, take a break from your exercise and continue consuming the contents of this article. What you haven't learnt here so far is good enough.

Maths methods

JavaScript has a maths object which is available to us by default (we'll understand what default means in this case when we talk about the global object).

This maths object has a handful of methods that we can use to perform mathematical operations with numbers.

๐Ÿ’ก
Tip: Recall that we can get a list of all properties/methods in an object by using the dot (.) notation just next to the object name without any whitespace. If you want to see all the contents of an object in tabular form, run this code console.table(objName) So, to see all contents of the math object, we do console.table(math)

Note that we are not calling these methods on the numbers e.g., age.abs() but we are rather passing the numbers into these functions are arguments. The function belongs to the math object and not the number variable. There is a difference.

If it belongs to the number variable, we would do age.toFixed(). We can describe that as calling the toFixed() method of the age variable.

When we do math.abs(), we are calling the abs() function of the math object.

Having made that clarification, let's learn about a few of the available Math methods and properties;

  • abs(x): The name abs is short for absolute. This function will simply return the absolute value of any number passed into it as an argument.

      console.log(Math.abs(-1)); // 1
      console.log(Math.abs(1)); // 1
      console.log(Math.abs(2.0)) // 2
      console.log(Math.abs(2.45)) // 2.45
      console.log(Math.abs(2.450)) // 2.45
    

    Math.abs() will try to coerce its argument into a number and if this operation doesn't work, the result will be NaN.

  • ceil(x): Initially, I understood this method by relating it to a ceiling (the upper interior surface of a room or other similar). I used this to recall that this method has to do with the rounding up of numbers. It rounds a number up to the smallest number greater than or equal to the provided argument passed into it.

      Math.ceil(-0); // -0
      Math.ceil(-9.04); // -9
      Math.ceil(-6); // -6
      Math.ceil(0.6); // 1
      Math.ceil(4); // 4
    
    ๐Ÿ’ก
    ceil() always rounds up. Irrespective of the rules you may think of when it comes to rounding numbers.
  • floor(x): The floor() method works like ciel() but it always rounds down. It returns the smallest integer greater than or equal to the argument passed into it (x).

    ๐Ÿ’ก
    Try this: Run the Math.floor() function yourself using different numbers all the way and observe how it works.
  • PI: This is not a method but a property which holds the value of the mathematical constant pie (ฯ€). That is all it does. Notice that PI is in all uppercase (it is a constant).

      console.log(Math.PI); // 3.141592653589793
    
  • round(): This method is used to round numbers to the nearest integer. This means that this method follows the mathematical rule for rounding floating point numbers to integers.

    In case you have forgotten or you do not know how this works in mathematics, if you are required to round a floating point value e.g, 2.45 to its nearest integer, you have to check if the decimal place is greater than 0.5 and if it is, then you add 1 to the integer value of the argument else, it just simply returns the integer part of the argument.

    The round method does the same thing and returns the integer.

      console.log(Math.round(2.40)); // 2
      console.log(Math.round(3.0)); // 3
      console.log(Math.round(2.5)); // 3
    
  • random(): The random method is used to generate a random floating point value between 0 and 1.

      console.log(Math.random()); // it generates a random value everytime.
    

    This method can be manipulated to generate random numbers within even larger ranges with some mathematical trick.

      // Create a function that generates a random number from 0 to 
      // any value specified. Ensure your 
      // function uses Math.random internally.
    
      function generateRandomNumber (upperBound) {
          return Math.floor(Math.random() * upperBound);
      }
    

    In the above snippet, we were able to write out our own function to generate a random number from 0 to any range we choose. We can even go further to make the function allow its user to provide a range of numbers from which to select a random number.

Exercises

  • Write a function to generate random numbers. Allow its user to provide a range of numbers from which to select a random number e.g., random(2, 9) should produce a random number between 2 and 9 with both numbers inclusive.

  • Write a function that takes two arguments base, exponent and returns the value of the base raised to the power of the exponent e.g., raise(2, 2 should return 4.

    ๐Ÿ’ก
    Tip: use Math.pow()
  • Write a function which returns the square root of the value passed into it.

    ๐Ÿ’ก
    Tip: Use Math.sqrt()

Let's quickly put together what we've learnt today.

SUMMARY

What If I told you there is more to the JavaScript number than what we have discussed so far? Yes, there is!

Those are either advanced aspects of the subject that you could get away with not knowing now and learn in the future when you have become more comfortable using the language and understood its syntax. If any issue arises from your ignorance of them, you will be able to find your way, gain knowledge about it and fix it.

You don't have to bug your brain about these aspects now because you will most likely forget you ever learnt it unless there's a use case for it - which is not a common thing.

Today we have learnt about the number variable and some of the most used methods it provides out of the box, and also the Math object and the methods available to us which we can use when working with numbers.

It is now left for programmers to take initiative with what's available to solve real-world problems.

In the next article, we are going to discuss different arithmetic (prefix, infix) and assignment operators in JavaScript.

Do not forget to like this post if it was helpful (you can like it up to 10 times), drop your questions or share your thoughts in the comment section and also subscribe to my newsletter to get updates whenever I release a new episode (scroll down to find the subscribe box)**.