javascript 取除法的整數與商數

Posted in :

在 JavaScript 中,將兩個變數相除,結果會是浮點數,javascript 沒有 int() 可以使, 請改用 Math.floor()。

var a = 13;
var b = 5;
var quo = Math.floor(a/b);
var rem = a%b;
console.log('Quotient = ',quo,'Remainder = ',rem);

輸出:

Quotient =  2 Remainder =  3

附註: 如果數字太大,Math 庫將失敗。請改用 Math.trunc() 函式,與 Math.floor() 函式相比,它可以處理大數字。Math.floor() 函式在負數的情況下會失敗,但 Math.trunc() 不會在負數的情況下失敗。


Math.round(x) 四捨五入,如
Math.round(0.60),結果為1
Math.round(0.49),結果為0

Math.floor(x) 向下捨入,如
Math.floor(0.60)
Math.floor(0.49),結果均為0;

Math.ceil(x)向上捨入,如
Math.ceil(0.60)
Math.ceil(0. 49),結果均為1。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *