需求:浮點數精度導致的數值計算問題,需要對數值計算進行格式化處理,保留小數位爲截取,不進行四捨五入
/**
* 帶基數、後綴的數值格式化
* @param {*} num 源數據
* @param {*} base 特定的基數(比如100, 1000)
* @param {*} decimals 保留的小數位數(只截取不進位)
* @param {*} suffix 需要帶的後綴
* @param {*} defaultStr 沒數據時的默認值
*/
export const numDecimalsSuffix = (num, base, decimals, suffix, defaultStr) => {
if (isNaN(num) || (!num && num !== 0)) {
return defaultStr ? defaultStr : '--'
}
let tempNum = base ? Number(num) * base : Number(num)
let dec = decimals ? decimals : 2
const formatNum = (number, digit) => {
// pow() 方法可返回 x 的 y 次冪的值
let power = Math.pow(10, digit)
// 源數據爲整數或者小數點後面小於decimals位的不處理
let pointIndex = String(number).indexOf('.') + 1 //獲取小數點的位置 + 1
let pointCount = pointIndex ? String(number).length - pointIndex : 0 //獲取小數點後的個數(需要保證有小數
// 默認爲兩位小數點
if (pointIndex === 0 || pointCount <= dec) {
return number
}
let realVal = ''
// 截取當前數據到小數點後decimals位
realVal = `${String(number).split('.')[0]}.${String(number).split('.')[1].substring(0, dec)}`
return Math.floor(realVal * power) / power
}
tempNum = formatNum(tempNum, dec)
// 判斷截取之後數值是否爲0
if (tempNum == 0) {
tempNum = 0
}
if (suffix) {
tempNum = `${tempNum}${suffix}`
}
return tempNum
}
eg: numDecimalsSuffix(1345.123, 1, 2, ' ', '--') ==> 1345.12
numDecimalsSuffix(1345.126, 1, 2, ' ', '--') ==> 1345.12
numDecimalsSuffix(0.1 + 0.2, 1, 2, ' %', '--') ==> 0.3%
numDecimalsSuffix(3.1799, 1, 2, ' %', '--')) ==> 3.17%
numDecimalsSuffix(3.17123, 100, 2, "%", "") ==> 317.12%