Javascript jQuery 圆函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4908552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:42:11  来源:igfitidea点击:

jQuery round function

javascriptjquery

提问by Sergio

How can I round the number using jQuery?

如何使用 jQuery 四舍五入这个数字?

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

如果数字是 3168,我想把它打印为 32。或者如果数字是 5233,结果应该是 52。

How can I do that? Should I use the Math.roundfunction?

我怎样才能做到这一点?我应该使用该Math.round功能吗?

回答by Dan Grossman

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

是的,您应该使用 Math.round(除以 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.

jQuery 是一个建立在 JavaScript 之上的用于 DOM 遍历、事件处理和动画的库。它不会取代 JavaScript,也不会重新实现其所有基本功能。

回答by Brad Christie

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 /100portion)

我假设你的意思是除以 100,然后舍入?或者你的意思是有小数位?(在这种情况下,请删除该/100部分)

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

此外,这只是基本的 JavaScript。正如另一位用户所提到的,jQuery 用于处理文档本身,而不是执行数学运算。



And here is a snippet from the jQuery math library1:

这是来自 jQuery 数学库1的片段:

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

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

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

1仅用于幽默——这种功能由 JavaScript 本身提供开箱即用的功能。

回答by Neo

<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.

Math.round 方法完全符合您的要求,不仅限于 ceil 或 floor。它将四舍五入到最近的整数。

回答by AuthorProxy

You can use this one :) roundMe(1.2345, 4)

你可以用这个:) 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;
 }

回答by Cymen

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.

如果您使用的是 javascript Number 对象,则可以使用该toFixed()方法。我假设这些数字缺少小数点。如果不是,除以 100 和以上。