AutoDecimal:轻松解决 JavaScript 运算精度问题
AutoDecimal:轻松解决 JavaScript 运算精度问题之跳过转换
AutoDecimal:轻松解决 JavaScript 运算精度问题之显式转换
AutoDecimal:轻松解决 JavaScript 运算精度问题之toDecimal
AutoDecimal:轻松解决 JavaScript 运算精度问题之new Function
支持 new Function
默认情况下,AutoDecimal 仅会处理计算表达式,当启用了 supportString 属性时,也仅仅会处理计算表达式中的数字字符串。
// AutoDecimal 默认参数下
const a = 0.1
const c = a + '0.2'
console.log(c) // "0.10.2"
当 supportString 为 true 时
const a = 0.1
const c = a + '0.2'
console.log(c) // 0.3
但是下面的却不会进行转换
const fn = new Function('a', 'b', 'return a + b')
const result = fn(0.1, 0.2)
console.log(result) // 0.30000000000000004
因为 fn 是通过 new Function 使用字符串创建的函数,而 AutoDecimal 仅处理计算表达式,但是不会处理字符串。所以当遇到字符串时,会自动跳过(即使 supportString 为 true)。
所以如果想要 AutoDecimal 处理用于创建 new Function 所需要的字符串时,需要启用 supportNewFunction。
// vite.config.ts
export default defineConfig({
plugins: [
AutoDecimal({
supportNewFunction: true
})
]
})
此时
const fn = new Function('a', 'b', 'return a + b')
const result = fn(0.1, 0.2)
console.log(result) // 0.3
启用 supportNewFunction 后,在 new Function 中如果想要使用 toDecimal 的话,需要单独启用。
// vite.config.ts
export default defineConfig({
plugins: [
AutoDecimal({
supportNewFunction: {
// 默认 false
// toDecimal: true
toDecimal: {
// toDecimal 参数
callMethod: 'toNumber'
}
}
})
]
})