Javascript提供了一些常見的數學函數,包含亂數(random)、無條件進位(ceil)、無條件捨去(floor)、指數(power)、平方根(sqrt)、絕對值(abs)...詳細函數可以在這裡查詢,以下僅介紹部分常用函數
Math.random(),回傳值範圍為 0 <= x < 1
Math.round(x),回傳 x 四捨五入後的整數值。
Math.floor(x),回傳 x 無條件捨去後的整數值。
Math.ceil(x),回傳 x 無條件進位後的整數值。
Math.abs(x),回傳 x 的絕對值。
Math.pow(x,n),回傳 x 的 n 次方。
Math.pow(x),回傳 x 的平方根。
結果:
亂數 random():95.74151793734438 [ Math.round()*100 ]
四捨五入 round(x):96 [ Math.round(rnd) ]
無條件捨去 floor(x):95 [ Math.floor(rnd) ]
無條件進位 ceil(x):96 [ Math.ceil(rnd) ]
絕對值 abs(x):35.5 [ Math.abs(-35.5) ]
指數 pow(x,n):128 [ Math.pow(2,7) ]
平方根 sqrt(x):16 [ Math.sqrt(256) ]
四捨五入 round(x):96 [ Math.round(rnd) ]
無條件捨去 floor(x):95 [ Math.floor(rnd) ]
無條件進位 ceil(x):96 [ Math.ceil(rnd) ]
絕對值 abs(x):35.5 [ Math.abs(-35.5) ]
指數 pow(x,n):128 [ Math.pow(2,7) ]
平方根 sqrt(x):16 [ Math.sqrt(256) ]