Browse Source

feat: [基础模板] 数字相加或相乘保留最长的小数位数

lkf
memorylkf 2 months ago
parent
commit
23a5de0252
2 changed files with 66 additions and 11 deletions
  1. +56
    -1
      src/utils/calUnitTools.js
  2. +10
    -10
      src/utils/formPackageCommon.js

+ 56
- 1
src/utils/calUnitTools.js View File

@ -12,10 +12,65 @@ export function addTj(valueArr, unitArr) {
let total = 0
for (let i = 0; i < unitArr.length; 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 {
total: total,
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
}

+ 10
- 10
src/utils/formPackageCommon.js View File

@ -1,11 +1,11 @@
//判断是否显示其他输入框
export const isShowOther=(v = [],col)=> {
if(col &&!col.otherCode){
return false;
}
// 确保v是数组类型,以避免类型错误
const arr = Array.isArray(v) ? v : [v];
const otherArr = ["其他","遮光","CA-QC Dilution_"]
//和凡哥商量,只要value为负数都显示其他
return arr.some(item => otherArr.includes(item));
}
export const isShowOther = (v = [], col) => {
if (col && !col.otherCode) {
return false
}
// 确保v是数组类型,以避免类型错误
const arr = Array.isArray(v) ? v : [v]
const otherArr = ['其他', '遮光', 'CA-QC Dilution-']
//和凡哥商量,只要value为负数都显示其他
return arr.some((item) => otherArr.includes(item))
}

Loading…
Cancel
Save