2012-02-08 28 views
0

如何忽略其餘或十進制值: 例子:var x = 5/2; 結果:x = 2.5; 我要的是,無論十進制值將被忽略,因此最終的輸出應爲x = 2;的Javascript整數

回答

5

你可以使用Math.floor()(向下舍入),Math.ceil()(舍入)或Math.round()(舍入到最接近的整數),取決於您想如何刪除小數。

實施例:

如果x = 2.5Math.floor(x) = 2Math.ceil(x) = 3Math.round(x) = 3

僅供參考:

檢查小提琴http://jsfiddle.net/BVYDR/

3

|運營商強制通過向零舍入其參數的整數值。

(3.141592654 | 0) === 3 
+0

整蠱,但它可以慢http://jsperf.com/math-floor-vs-math-round-vs-parseint/2 – Alfabravo 2012-02-08 07:19:43

3

parseInt(5/2)會給你2