# JavaScript 小數四捨五入 ###### tags: `JavaScript` `round` `decimal` 在 JavaScript 數字型態是 float ,會有浮點數誤差,所以用 `Math.round()` 或 `Number.toFixed()` 取小數四捨五入得到的答案在某些情況下會跟平常的答案不同。 試過很多不同的方式,[這篇文章](https://liaosankai.pixnet.net/blog/post/28479797)所列的算法,測試幾次得到的答案都跟平常四捨五入的相同,故做個紀錄供參考。 ```javascript= roundX(val, precision) { //小數四捨五入(數字, 位數) return ( Math.round( Math.round(val * Math.pow(10, (precision || 0) + 1)) / 10 ) / Math.pow(10, precision || 0) ); } ```