我有這個號碼:-0.0166667,我想只得到兩個浮動的數字,因此數字應該是-0.01獲得2個位數的預期浮點數不工作
我想這
-0.0166667.toFixed(2) # gives : -0.02
而且這個
Math.round(-0.0166667 * 100)/100 # also gives : -0.02
但他們兩人的變換數-0.02,而不是-0.01
這裏有什麼問題?
我有這個號碼:-0.0166667,我想只得到兩個浮動的數字,因此數字應該是-0.01獲得2個位數的預期浮點數不工作
我想這
-0.0166667.toFixed(2) # gives : -0.02
而且這個
Math.round(-0.0166667 * 100)/100 # also gives : -0.02
但他們兩人的變換數-0.02,而不是-0.01
這裏有什麼問題?
按位或截斷小數部分使用|
。
var x = (-0.0166667 * 100 | 0)/100,
y = (0.0166667 * 100 | 0)/100;
document.write(x + '<br>' + y);
一個更好的解決方案,節省了標誌,適用於地板,放籤回。
function toFixed(x, digits) {
return (x < 0 ? - 1 : 1) * Math.floor(Math.abs(x) * Math.pow(10, digits))/Math.pow(10, digits);
}
document.write(toFixed(-0.0166667, 2) + '<br>');
document.write(toFixed(0.0166667, 2) + '<br>');
document.write(toFixed(-0.0166667, 3) + '<br>');
document.write(toFixed(0.0166667, 3) + '<br>');
對於小於零之間的數字,Math.ceil
截斷沒有四捨五入和數字大於零Math.floor
工作正常。當你的號碼是小於壽所以使用Math.ceil
代替
Math.ceil(-0.0166667 * 100)/100
編輯
編寫自定義輔助方法來截斷浮點
function truncate(num) {
return num > 0 ? Math.floor(num) : Math.ceil(num);
}
和回合數過了2數字使用
truncate(num * 100)/100
這也會使正數向上舍入。截斷是「舍入到零」。 –
Math.round
會將數字四捨五入爲最接近的整數,所以您的代碼的輸出實際上是正確的。你需要的是截斷而不是四捨五入。下面是做到這一點的最簡單的方法:
function toZero(x) {
return x > 0 ? Math.floor(x) : Math.ceil(x);
}
function round2digits(x) {
return toZero(x * 100)/100;
}
document.write(round2digits(-0.0166)); // prints `-0.01`
所以你不想四捨五入,而是截斷? –
無法讓jsPerf立即工作,但我不明白爲什麼substring()在這裏不起作用,如果你只是截斷 – colonelsanders