开发者

JavaScript rounding numbers

开发者 https://www.devze.com 2023-01-31 20:36 出处:网络
I know that I can round a number like this 开发者_运维技巧 var number = 1.3; Math.round(number); and the result I\'m given is 1.

I know that I can round a number like this

开发者_运维技巧
var number = 1.3;
Math.round(number);

and the result I'm given is 1.

But how can I round a number to the next highest whole number? So round 1.3 to 2 instead of 1?


Use Math.ceil() instead. It rounds the number up.


var rounded = Math.ceil(number);

As an aside, in platforms with no ceil method available, and assuming round rounds to the nearest integer, a common trick used to round upwards is:

var rounded = Math.round(number + 0.5);


Don't forget Math.floor(number)!

Although, I would recommend against using javascript to do arithmetic... I don't know the exact reasons (but i just asked a question =P).

0

精彩评论

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