简体   繁体   English

javascript使数字为150的倍数

[英]javascript make a numbers to be multiples of 150

I'm trying to get numbers to be multiples of 150. 我正在尝试使数字为150的倍数。

(all the num > 0)

if num = 0.333333 => output 150
if num = 149.9 => output 150
if num = 150 => output 150
if num = 150.1 => output 300
if num = 302 => output 450
...

Here is my code so far, using ceil() : 到目前为止,这是我使用ceil()代码:

var num = '12';
document.write(Math.ceil((num/150)*150) + "<br />")
// Output 12, not 150;

How can I do this? 我怎样才能做到这一点?

You almost had it. 你差点就吃了。 Simply multiply after the rounding operation: 四舍五入后只需乘以:

function ceil150(x) {
    return Math.ceil(x / 150) * 150;
}

alert(ceil150(0.333333));
alert(ceil150(149.9));
alert(ceil150(150));
alert(ceil150(150.1));
alert(ceil150(302));

http://jsfiddle.net/WEdSu/ http://jsfiddle.net/WEdSu/

This is simple algebra, sir: 先生,这是简单的代数:

(num / 150) * 150 = num

Substituting '12' (yes, a string): 替换为'12' (是,字符串):

(num / 150) * 150 = 12

If you want all numbers to map to multiples of 150 , then just divide them by 150 and then floor the result to get an integer: 如果您希望所有数字都映射为150倍数,则只需将它们除以150, 然后 floor即可得到整数:

150 * math.floor(num / 150)

Or ceil it: 或将其ceil

150 * math.ceil(num / 150)

A simple way would be 一种简单的方法是

var num = 12;
var result = 150 * Math.ceil((num * 1.0)/150);

The multiplication by 1.0 ensures that input is converted to a floating point value - otherwise you may end up with integer division and get 12 / 150 = 0. 乘以1.0可确保将输入转换为浮点值-否则,您可能会得到整数除法并得到12/150 = 0。

var num = '12';
document.write(Math.ceil(num/150)*150) + "<br />")

Your parentheses were off by just a little. 您的括号只差了一点。

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

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