JQuery round function

How can I round a number using jQuery?

If the number is 3168, I want to print it as 32. Or, if the number is 5233, the result should be 52.

How can i do this? Should I use the Math.round function?

+4
source share
5 answers

Yes, you should use Math.round (after dividing by 100).

jQuery is a library for traversing the DOM, handling events and animations created on top of JavaScript. It does not replace JavaScript and does not override all its basic functions.

+38
source
 var num = 3168; $('#myElement').text(Math.round(num/100)); 

I assume you mean divide by 100, then round? Or did you mean decimal places? (In this case, remove the /100 part)

Also, this is just basic JavaScript. As another user noted, jQuery should work with the document itself, and not perform mathematical operations.


And here is a fragment from the jQuery 1 math library:

 (function($){ $.round = Math.round; })(jQuery); $.round(3168 / 100) // 32 $.round(5233 / 100) // 52 

1 For humor only - this functionality is provided by JavaScript itself.

+10
source
 <script type='text/javascript'> function jqROund(a) { return Math.round(a/100); } </script> <input type='text' id='numba' value='3168'> <input type='button' onclick="alert( jqRound($('#numba').val() ) );"> 

The Math.round method does exactly what you want, and not just the ceiling or the floor. He rounds it to the nearest whole.

+3
source

If you are using a Javascript Number object, you can use the toFixed() method. I assume that these numbers do not have a decimal point. If not, divide by 100 and as above.

+1
source

You can use this: roundMe(1.2345, 4)

 function roundMe(n, sig) { if (n === 0) return 0; var mult = Math.pow(10, sig - Math.floor(Math.log(n < 0 ? -n: n) / Math.LN10) - 1); return Math.round(n * mult) / mult; } 
+1
source

Source: https://habr.com/ru/post/1338566/


All Articles