轉載 https://blog.csdn.net/qq_39571197/article/details/87597062
1、定義和用法,都是對數字進行四捨五入操作
Math.round()方法,可把一個數字舍入爲最接近的整數。
toFixed()方法,可把 Number 四捨五入爲指定小數位數的數字。
2、返回值的類型不同
-
const num = 123;
-
console.log(typeof(num.toFixed())); // "string"
-
console.log(typeof(Math.round(num))); // "number"
Math.round()方法,返回值爲數字。
toFixed()方法,返回值爲字符串。
3、處理精度不同
-
const num = 100.153;
-
console.log(num.toFixed(2)); // 100.15
-
console.log(num.toFixed(1)); // 100.1
-
console.log(num.toFixed()); // 100
-
-
console.log(Math.round(num)); // 100
Math.round()方法,就一個參數,而且用法也說明了,只返回整數。
toFixed()方法,可以接受第二個參數,用來規定小數位數,範圍是2-20~
計算時需要 字符串轉數字
parseFloat(((0.1 + 0.2)*10).toFixed(10))