简体   繁体   English

修改楼层/天花板功能以使用1以外的数字?

[英]Modify floor/ceiling function to work with numbers other than 1?

By default the floor function always rounds down and the ceil function always rounds up to the nearest '1' 默认情况下,floor函数总是向下舍入,ceil函数总是向上舍入到最接近的'1'

How would I round down/up to the nearest 20, or the nearest 1,000? 我如何向下/向上舍入到最近的20,或最接近的1000?

Say I had a number x and a factor y. 假设我有一个数字x和一个因子y。

I want to find the closest factor of y to x. 我想找到y与x的最接近的因子。

I am using this to find maximum and minimum values for a graph. 我用它来查找图表的最大值和最小值。 Thanks. 谢谢。

简单:

var z = y * Math.floor(x / y);
Math.floor(x / 20) * 20;
Math.ceil(x / 20) * 20;

In your case: 在你的情况下:

Math.floor(x / y) * y;

The x / y turns the expression into units of y ; x / y将表达式转换units of y ; with .floor() or .ceil() you then round it down or up; 使用.floor().ceil()然后向下或向上舍入; afterwards you multiply with y again to get your final answer. 之后再次乘以y得到你的最终答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM