import BigNumber from 'bignumber.js' import { useRound } from '@/commonMethods/useRound' /** * 转换科学计数法 * @param value 小数 * @param notationDigit 计数法保留小数位数(四舍五入) 1.2344444e-5 -> 1.234e-5 * @param numberDigit 计数法保留小数位数(四舍五入) 1.2344444e-5 -> 1.234e-5 * @param standard 转换标准 小于这个数才会转化为科学计数法 * @returns 科学计数法 */ export function useScientificNotation(value: number | string, notationDigit = 2, numberDigit = 2, standard = 0.001) { console.log(value, '未处理数据') var res = BigNumber(value).toString() if (res.includes('E') || res.includes('e')) { res = res.replace('E', 'e') // 如果本身就是科学计数法 return `${useRound(res.split('e')[0], notationDigit)}e${res.split('e')[1]}` } if (BigNumber(value).comparedTo(standard).toString() === '-1') { // 不是科学计数法(只处理小数) if (res.includes('.')) { // 寻找小数点 const pointIndex = res.indexOf('.') // 负数 if (res.includes('-')) { if (res.length - 1 - pointIndex < 4) { return res } if (Number(res[1]) > 0) { if (!String(numberDigit) || String(numberDigit) === '0') { return res } else { return useRound(value, numberDigit) } } } let digitsIndex = 0 for (let i = pointIndex + 1; i < res.length; i++) { if (Number(res[i]) > 0) { digitsIndex = i break } } if (digitsIndex === 0) { return res } const digitsNumber = useRound(`${res[digitsIndex]}.${res.substring(digitsIndex + 1, res.length)}`, notationDigit) return `${res[0] === '-' ? '-' : ''}${digitsNumber}e-${digitsIndex - pointIndex}` } else { return res } } else { return res } }