简体   繁体   中英

javascript make a numbers to be multiples of 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 => 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?

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/

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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