feat:设备使用记录
This commit is contained in:
@@ -327,6 +327,79 @@ export function handleRoundFiveNumber(number, fixed = 0) {
|
||||
//偶不进,将取值的当前位数,直接截取字符即可
|
||||
return number.substr(0, indexFixed)
|
||||
}
|
||||
export function handleEfficaciousNumber(number, fixed, effectiveDigit) {
|
||||
// 1. 先将数字补全到 fixed 位小数
|
||||
const numStr = String(number)
|
||||
const dotIndex = numStr.indexOf('.') // dotIndex = 1
|
||||
let actualFixed = fixed // 默认为 fixed
|
||||
|
||||
if (dotIndex !== -1) {
|
||||
const decimalPart = numStr.slice(dotIndex + 1) // decimalPart = "0400"
|
||||
console.log(`小数部分: ${decimalPart}`)
|
||||
|
||||
let nonZeroCount = 0
|
||||
let targetEffectiveDigitPos = -1
|
||||
|
||||
// 2. 循环 "0400",寻找有效数字
|
||||
for (let i = 0; i < decimalPart.length; i++) {
|
||||
// i=0 to 3
|
||||
const char = decimalPart[i]
|
||||
console.log(`检查第 ${i + 1} 位: '${char}', 当前 nonZeroCount: ${nonZeroCount}`)
|
||||
|
||||
if (nonZeroCount === 0) {
|
||||
// 寻找第一个非零数字
|
||||
if (char !== '0') {
|
||||
// i=0, '0' -> false; i=1, '4' -> true
|
||||
nonZeroCount++ // nonZeroCount = 1
|
||||
console.log(` -> 找到第 1 个有效数字: '${char}'`)
|
||||
}
|
||||
} else {
|
||||
// 已经找到第一个非零数字,后续所有数字都算有效
|
||||
if (nonZeroCount < effectiveDigit) {
|
||||
// 1 < 2 -> true
|
||||
nonZeroCount++ // nonZeroCount = 2
|
||||
console.log(` -> 找到第 2 个有效数字: '${char}'`)
|
||||
}
|
||||
}
|
||||
|
||||
if (nonZeroCount === effectiveDigit) {
|
||||
// 2 === 2 -> true when i=2
|
||||
targetEffectiveDigitPos = i + 1 // i=2, so pos is 3
|
||||
console.log(` -> 目标有效数字 (${effectiveDigit}) 已找到,位于第 ${targetEffectiveDigitPos} 位`)
|
||||
break
|
||||
}
|
||||
}
|
||||
console.log(`targetEffectiveDigitPos: ${targetEffectiveDigitPos}`)
|
||||
|
||||
// 3. 判断并设置最终精度
|
||||
if (targetEffectiveDigitPos !== -1 && targetEffectiveDigitPos <= fixed) {
|
||||
// 3 !== -1 and 3 <= 4 -> true
|
||||
actualFixed = targetEffectiveDigitPos // actualFixed = 3
|
||||
}
|
||||
const finalNumber = handleRoundFiveNumber(Number(number), actualFixed)
|
||||
// 获取整数部分
|
||||
const finalIntegerPart = finalNumber.slice(0, dotIndex + 1) // 包含小数点
|
||||
const finalDecimalPart = finalNumber.slice(dotIndex + 1)
|
||||
// 截取指定长度的小数部分
|
||||
let truncatedDecimalPart = ''
|
||||
if (Number(finalDecimalPart) === 0) {
|
||||
truncatedDecimalPart = finalDecimalPart.substring(0, effectiveDigit)
|
||||
}else{
|
||||
truncatedDecimalPart = finalDecimalPart.substring(0, actualFixed)
|
||||
}
|
||||
|
||||
|
||||
// 拼接最终结果
|
||||
let result = finalIntegerPart + truncatedDecimalPart
|
||||
|
||||
// 特殊情况处理:如果截取后小数部分为空,则去掉小数点
|
||||
if (actualFixed === 0) {
|
||||
result = finalIntegerPart.slice(0, -1) // 去掉最后的 "."
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
** 除法函数,用来得到精确的除法结果
|
||||
|
||||
Reference in New Issue
Block a user