round till 2 digit in jquery

How to round till 2 digits in jQuery

When working with numbers in jQuery, you may come across situations where you need to round a number to a specific number of digits. In this case, we will focus on rounding a number till 2 digits.

Method 1: Using toFixed()

The easiest way to round a number till 2 digits is by using the toFixed() method. This method converts a number into a string, keeping only the specified number of decimals.


    let num = 3.14159265359;
    let roundedNum = num.toFixed(2);
    console.log(roundedNum); // Output: 3.14

Method 2: Using Math.round()

If you want to round a number to the nearest integer, you can use the Math.round() method. To round till 2 digits, you can first multiply the number by 100, then use Math.round(), and finally divide by 100.


    let num = 3.14159265359;
    let roundedNum = Math.round(num * 100) / 100;
    console.log(roundedNum); // Output: 3.14

Method 3: Using Math.floor() or Math.ceil()

If you want to always round down or up, you can use the Math.floor() or Math.ceil() method respectively. Similar to Method 2, you can first multiply the number by 100, then use Math.floor() or Math.ceil(), and finally divide by 100.


    let num = 3.14159265359;
    let roundedDownNum = Math.floor(num * 100) / 100;
    console.log(roundedDownNum); // Output: 3.14

    let roundedUpNum = Math.ceil(num * 100) / 100;
    console.log(roundedUpNum); // Output: 3.15

These are the three ways in which you can round a number till 2 digits in jQuery. Choose the method that best fits your needs and use it in your code.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe