开发者

javascript make a numbers to be multiples of 150

开发者 https://www.devze.com 2023-04-10 23:12 出处:网络
I\'m trying to get numbers to be multiples of 150. (all the num > 0) if num = 0.333333 => output 150

I'm trying to get numbers to be multiples of 150.

(all the num > 0)

if num = 0.333333 => output 150
if num = 149.9 => output 150
if num = 150 开发者_如何学C=> output 150
if num = 150.1 => output 300
if num = 302 => output 450
...

Here is my code so far, using ceil():

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

How can I do this?


This is simple algebra, sir:

(num / 150) * 150 = num

Substituting '12' (yes, a string):

(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 * math.floor(num / 150)

Or ceil it:

150 * math.ceil(num / 150)


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/


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.


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

Your parentheses were off by just a little.

0

精彩评论

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

关注公众号