开发者

jQuery round function

How can I round the 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 that? Should I use the Math.round fun开发者_StackOverflowction?


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

jQuery is a library for DOM traversal, event handling and animation built on top of JavaScript. It doesn't replace JavaScript and doesn't reimplement all its basic functions.


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

I assume you mean divide by 100, then round? Or did you mean to have decimal places? (In which case, remove the /100 portion)

Also, this is just basic JavaScript. As another user mentioned, jQuery is to work with the document itself, not to perform math operations.


And here is a snippet from the jQuery math library1:

(function($){
  $.round = Math.round;
})(jQuery);

$.round(3168 / 100) // 32
$.round(5233 / 100) // 52

1 Meant for humor only--this kind of functionality is provided out-of-the-box by JavaScript itself.


<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 you want and does not only ceil, or floor. It will round it to the nearest Integer.


If you're using the javascript Number object you can use the toFixed() method. I'm assuming those numbers are missing the decimal point. If not, divide by 100 and as above.


You can use this one :) 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;
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜