Javascript 使用舍入到最接近的 10

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11022488/
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-24 04:03:58  来源:igfitidea点击:

Javascript using round to the nearest 10

javascript

提问by mark denfton

I would like to round integers using JavaScript. For example:

我想使用 JavaScript 对整数进行四舍五入。例如:

10 = 10
11 = 20
19 = 20
24 = 30
25 = 30
29 = 30

回答by alexn

This should do it:

这应该这样做:

Math.ceil(N / 10) * 10;

Where N is one of your numbers. However, this does not work for your first case (10 rounds to 20, but why would it?).

其中 N 是您的数字之一。但是,这不适用于您的第一种情况(10 轮到 20 轮,但为什么会这样?)。

回答by kennebec

To round a number to the next greatest multiple of 10, add one to the number before getting the Math.ceil of a division by 10. Multiply the result by ten.

要将数字四舍五入到 10 的下一个最大倍数,请在得到除以 10 的 Math.ceil 之前的数字加 1。将结果乘以 10。

Math.ceil((n+1)/10)*10;

Math.ceil((n+1)/10)*10;

1->10
2->10
3->10
4->10
5->10
6->10
7->10
8->10
9->10
10->20
11->20
12->20
13->20
14->20
15->20
16->20
17->20
18->20
19->20
20->30
21->30
22->30
23->30
24->30
25->30
26->30
27->30
28->30
29->30
30->40
35-> 40
40-> 50
45-> 50
50-> 60
55-> 60
60-> 70
65-> 70
70-> 80
75-> 80
80-> 90
85-> 90
90-> 100
95-> 100
100-> 110

回答by Niet the Dark Absol

Math.round()rounds to the nearest integer. To round to any other digit, divide and multiply by powers of ten.

Math.round()舍入到最接近的整数。要四舍五入到任何其他数字,请除以乘以十的幂。

One such method is this:

一种这样的方法是这样的:

function round(num,pre) {
    if( !pre) pre = 0;
    var pow = Math.pow(10,pre);
    return Math.round(num*pow)/pow;
}

You can make similar functions for floorand ceiling. However, no matter what you do, 10will never round to 20.

您可以为floor和制作类似的功能ceiling。但是,无论您做什么,10都永远不会舍入到20

回答by silly

or this

或这个

var i = 20;
var yourNumber = (parseInt(i/10, 10)+1)*10;