华西海圻ELN前端工程
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.2 KiB

  1. //体积不同单位相加
  2. export function addTj(valueArr, unitArr) {
  3. let unit = ['pL', 'nL', 'uL', 'mL', 'L']
  4. //计算最小单位
  5. let mixIndex = unit.length - 1
  6. for (let i = 0; i < unitArr.length; i++) {
  7. let thisIndex = unit.indexOf(unitArr[i])
  8. mixIndex = thisIndex < mixIndex ? thisIndex : mixIndex
  9. }
  10. let total = 0
  11. for (let i = 0; i < unitArr.length; i++) {
  12. let thisIndex = unit.indexOf(unitArr[i])
  13. total = addDecimals(
  14. total,
  15. multiplyDecimals(
  16. parseFloat(valueArr[i]),
  17. Math.pow(1000, thisIndex - mixIndex)
  18. )
  19. )
  20. // total += parseFloat(valueArr[i]) * Math.pow(1000, thisIndex - mixIndex)
  21. }
  22. return {
  23. total: total,
  24. unit: unit[mixIndex]
  25. }
  26. }
  27. export function addDecimals(a, b) {
  28. if (Number.isNaN(a) || Number.isNaN(b)) {
  29. return 0
  30. }
  31. const strA = a.toString()
  32. const strB = b.toString()
  33. // 获取小数位数
  34. const getDecimals = (str) => (str.split('.')[1] || '').length
  35. const maxLen = Math.max(getDecimals(strA), getDecimals(strB))
  36. // 相加并格式化为字符串
  37. const result = (parseFloat(a) + parseFloat(b)).toFixed(maxLen)
  38. // 去掉末尾的0
  39. return result.replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '')
  40. }
  41. export function multiplyDecimals(a, b) {
  42. if (Number.isNaN(a) || Number.isNaN(b)) {
  43. return 0
  44. }
  45. const strA = a.toString()
  46. const strB = b.toString()
  47. const decA = (strA.split('.')[1] || '').length
  48. const decB = (strB.split('.')[1] || '').length
  49. const totalDecimals = decA + decB
  50. const numA = BigInt(strA.replace('.', ''))
  51. const numB = BigInt(strB.replace('.', ''))
  52. const product = numA * numB
  53. const productStr = product.toString()
  54. const isNegative = productStr.startsWith('-')
  55. const absStr = isNegative ? productStr.substring(1) : productStr
  56. let result = ''
  57. if (totalDecimals === 0) {
  58. result = absStr
  59. } else if (absStr.length <= totalDecimals) {
  60. result = '0.' + absStr.padStart(totalDecimals, '0')
  61. } else {
  62. result =
  63. absStr.substring(0, absStr.length - totalDecimals) +
  64. '.' +
  65. absStr.substring(absStr.length - totalDecimals)
  66. }
  67. result = result.replace(/\.?0+$/, '') || '0'
  68. return (isNegative ? '-' : '') + result
  69. }