js 保留小數(四捨五入)

今天遇到筆試題,最後結果要求四捨五入保留小數後五位。當時沒想起怎麼作,後來考慮了一下。函數

用到的函數:prototype

  • Math.round() : 可把一個數字舍入爲最接近的整數(即四捨五入)
  • toFixed(n) : 保留n位小數
function round_retain(num, n) {
            // num: 要處理的數  n: 保留位數
            // 十進制向右移動n爲,而後利用 Math.round() 四捨五入,再向左移動n位,最後利用 toFixed() 保留小數
            return (Math.round(num * Math.pow(10, n)) / Math.pow(10, n)).toFixed(n);
        }

固然也能夠作一下判斷,n爲非負整數。code

function round_retain(num, n = 0) {
            if(Object.prototype.toString.call(n) === "[object Number]") {
                n =  parseInt(n);
            } else {
                throw new TypeError("請輸入小數保留位數爲正整數。");
            }
            if(n <= 0) {
                return Math.round(num);
            }
            
            return (Math.round(num * Math.pow(10, n)) / Math.pow(10, n)).toFixed(n);
        }

有更好的方法請在評論區告訴我,感謝你的觀看。io

相關文章
相關標籤/搜索