[英]How can I round to whole numbers in JavaScript?
我有以下代碼來計算某個百分比:
var x = 6.5;
var total;
total = x/15*100;
// Result 43.3333333333
我想要的結果是確切的數字43
,如果總數為43.5
,則應四舍五入為44
有沒有辦法在 JavaScript 中做到這一點?
使用Math.round()
函數將結果四舍五入到最接近的整數。
//method 1
Math.ceil(); // rounds up
Math.floor(); // rounds down
Math.round(); // does method 2 in 1 call
//method 2
var number = 1.5; //float
var a = parseInt(number); // to int
number -= a; // get numbers on right of decimal
if(number < 0.5) // if less than round down
round_down();
else // round up if more than
round_up();
一個或一個組合將解決您的問題
total = Math.round(total);
應該做。
使用Math.round
將數字四舍五入到最接近的整數:
total = Math.round(x/15*100);
用於舍入浮點數 x 的一個非常簡潔的解決方案:
x = 0|x+0.5
或者如果你只是想把你的浮子放在地板上
x = 0|x
這是按位或 int 0,它刪除小數點后的所有值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.