jQuery to round off decimal values

To round off decimal values using jQuery, we can use the built-in JavaScript methods toFixed() or toPrecision().

The toFixed() method converts a number into a string, keeping a specified number of decimals.

var iNum = 12345.6789;
iNum.toFixed();    // Returns "12346": note rounding, no fractional part
iNum.toFixed(1);   // Returns "12345.7": note rounding
iNum.toFixed(6);   // Returns "12345.678900": note added zeros

The toPrecision() method formats a number to a specified length.

var iNum = 5.123456;
iNum.toPrecision();    // Returns 5.123456
iNum.toPrecision(5);   // Returns 5.1235
iNum.toPrecision(2);   // Returns 5.1
iNum.toPrecision(1);   // Returns 5

But then you will be wondering how toPrecision() is different from toFixed()? Well, they are different.toFixed() gives you a fixed number of decimal places, whereas the other gives you a fixed number of significant digits.

var iNum = 15.667;
iNum.toFixed(2);        // Returns "15.67"
iNum.toPrecision(2);    // Returns "16"
iNum.toPrecision(3);    // Returns "15.7"

Feel free to contact me for any help related to jQuery, I will gladly help you.