1、toFixed並非四舍五入,而是四舍六入,是銀行家的舍入規則。
2、四舍六入五考慮,五後非零就進壹,五後為零看奇偶,五前為偶應舍去,五前為奇要進壹。
(0.356).toFixed(2)=0.36
(0.355).toFixed(2)=0.36
(0.3451).toFixed(2)=0.35
(0.3450).toFixed(2)=0.34
二、Math.floor()
1、向下取整,不管超過5不超過5,都要舍去。
Math.floor(1.4)=1
Math.floor(1.6)=1
三、Math.ceil()
1、向上取整,不管超過5不超過5,都向上取整。
Math.ceil(1.4)=2
Math.ceil(1.6)=2
四、Math.round()
1、是真正意義上的四舍五入。
Math.round(1.4)=1
Math.round(1.6)=2
五、保留兩位小數
1、無論整數還是小數都保留兩位小數,遵循四舍五入原則。
changeTwoDecimal_f(100)=100.00
changeTwoDecimal_f(100.333)=100.33
changeTwoDecimal_f(100.335)=100.34
function changeTwoDecimal_f(x) {
var f_x =parseFloat(x);
if (isNaN(f_x)) {
alert('function:changeTwoDecimal->parameter error');
return false;
}
var f_x = Math.round(x *100) /100;
var s_x = f_x.toString();
var pos_decimal = s_x.indexOf('.');
if (pos_decimal <0) {
pos_decimal = s_x.length;
s_x +='.';
}
while (s_x.length <= pos_decimal +2) {
s_x +='0';
}
return s_x;
}