|
|
@ -12,10 +12,65 @@ export function addTj(valueArr, unitArr) { |
|
|
let total = 0 |
|
|
let total = 0 |
|
|
for (let i = 0; i < unitArr.length; i++) { |
|
|
for (let i = 0; i < unitArr.length; i++) { |
|
|
let thisIndex = unit.indexOf(unitArr[i]) |
|
|
let thisIndex = unit.indexOf(unitArr[i]) |
|
|
total += parseFloat(valueArr[i]) * Math.pow(1000, thisIndex - mixIndex) |
|
|
|
|
|
|
|
|
total = addDecimals( |
|
|
|
|
|
total, |
|
|
|
|
|
multiplyDecimals( |
|
|
|
|
|
parseFloat(valueArr[i]), |
|
|
|
|
|
Math.pow(1000, thisIndex - mixIndex) |
|
|
|
|
|
) |
|
|
|
|
|
) |
|
|
|
|
|
// total += parseFloat(valueArr[i]) * Math.pow(1000, thisIndex - mixIndex)
|
|
|
} |
|
|
} |
|
|
return { |
|
|
return { |
|
|
total: total, |
|
|
total: total, |
|
|
unit: unit[mixIndex] |
|
|
unit: unit[mixIndex] |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
export function addDecimals(a, b) { |
|
|
|
|
|
const strA = a.toString() |
|
|
|
|
|
const strB = b.toString() |
|
|
|
|
|
|
|
|
|
|
|
// 获取小数位数
|
|
|
|
|
|
const getDecimals = (str) => (str.split('.')[1] || '').length |
|
|
|
|
|
const maxLen = Math.max(getDecimals(strA), getDecimals(strB)) |
|
|
|
|
|
|
|
|
|
|
|
// 相加并格式化为字符串
|
|
|
|
|
|
const result = (parseFloat(a) + parseFloat(b)).toFixed(maxLen) |
|
|
|
|
|
|
|
|
|
|
|
// 去掉末尾的0
|
|
|
|
|
|
return result.replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '') |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
export function multiplyDecimals(a, b) { |
|
|
|
|
|
const strA = a.toString() |
|
|
|
|
|
const strB = b.toString() |
|
|
|
|
|
|
|
|
|
|
|
const decA = (strA.split('.')[1] || '').length |
|
|
|
|
|
const decB = (strB.split('.')[1] || '').length |
|
|
|
|
|
const totalDecimals = decA + decB |
|
|
|
|
|
|
|
|
|
|
|
const numA = BigInt(strA.replace('.', '')) |
|
|
|
|
|
const numB = BigInt(strB.replace('.', '')) |
|
|
|
|
|
|
|
|
|
|
|
const product = numA * numB |
|
|
|
|
|
const productStr = product.toString() |
|
|
|
|
|
|
|
|
|
|
|
const isNegative = productStr.startsWith('-') |
|
|
|
|
|
const absStr = isNegative ? productStr.substring(1) : productStr |
|
|
|
|
|
|
|
|
|
|
|
let result = '' |
|
|
|
|
|
if (totalDecimals === 0) { |
|
|
|
|
|
result = absStr |
|
|
|
|
|
} else if (absStr.length <= totalDecimals) { |
|
|
|
|
|
result = '0.' + absStr.padStart(totalDecimals, '0') |
|
|
|
|
|
} else { |
|
|
|
|
|
result = |
|
|
|
|
|
absStr.substring(0, absStr.length - totalDecimals) + |
|
|
|
|
|
'.' + |
|
|
|
|
|
absStr.substring(absStr.length - totalDecimals) |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
result = result.replace(/\.?0+$/, '') || '0' |
|
|
|
|
|
return (isNegative ? '-' : '') + result |
|
|
|
|
|
} |