number-precision,一个js精度计算浮点数的库,但使用中传入异常数据会出现null.toString等的导致程序崩溃的error错误;
so我决定封装一下
被除数把null和undefined置为0
除数的null和undefined置为1
被成数把null和undefined置为0
成数的null和undefined置为0
加减法如果您有使用,可以参看我这个取处理吧~
// utils.ts
import NP from 'number-precision'
/**
* 去除null undefined ,NP执行toString导致的error异常
* 去除 * 0, / 0 导致的NaN
*/
export const NPNoEc = {
/**
* 精确除法
* ---
* num1 / num2 / other...
* @param num1
* @param num2
* @param others
* @returns number
*/
divide: (num1: number, num2: number, ...others: number[]): number => {
num1 = _.isNil(num1) ? 0 : num1
num2 = _.isNil(num2) || num2 === 0 ? 1 : num2
if (others.length > 0) {
return NPNoEc.divide(NPNoEc.divide(num1, num2), others[0], ...others.slice(1))
}
return NP.divide(num1, num2)
},
/**
* 精确乘法
* ---
* num1 * num2 * other...
* @param num1
* @param num2
* @param others
* @returns number
*/
times: (num1: number, num2: number, ...others: number[]): number => {
num1 = _.isNil(num1) ? 0 : num1
num2 = _.isNil(num2) ? 0 : num2
if (others.length > 0) {
return NPNoEc.times(NPNoEc.divide(num1, num2), others[0], ...others.slice(1))
}
return NP.times(num1, num2)
}
}
// utils.test.js
import { NPNoEc } from './utils'
import NP from 'number-precision'
test('NPNoEc.divide', () => {
expect(NPNoEc.divide(0, 0)).toBe(0)
expect(NPNoEc.divide(1, 0)).toBe(1)
expect(NPNoEc.divide(1, 1)).toBe(1)
expect(NPNoEc.divide(0, 1)).toBe(0)
expect(NPNoEc.divide(null, null)).toBe(0)
expect(NPNoEc.divide(null, 0)).toBe(0)
expect(NPNoEc.divide(0, null)).toBe(0)
expect(NPNoEc.divide(undefined, undefined)).toBe(0)
expect(NPNoEc.divide(null, undefined)).toBe(0)
expect(NPNoEc.divide(undefined, null)).toBe(0)
expect(NPNoEc.divide(undefined, 0)).toBe(0)
expect(NPNoEc.divide(0, undefined)).toBe(0)
for (let i = 0; i < 100; i++) {
const num = NPNoEc.divide(i, 100)
expect(num).not.toBeUndefined()
expect(num).not.toBeNull()
expect((num).toString().length).toBeLessThan(8)
}
});
test('NPNoEc.times', () => {
expect(NPNoEc.times(0, 0)).toBe(0)
expect(NPNoEc.times(1, 0)).toBe(1)
expect(NPNoEc.times(1, 1)).toBe(1)
expect(NPNoEc.times(0, 1)).toBe(0)
expect(NPNoEc.times(null, null)).toBe(0)
expect(NPNoEc.times(null, 0)).toBe(0)
expect(NPNoEc.times(0, null)).toBe(0)
expect(NPNoEc.times(undefined, undefined)).toBe(0)
expect(NPNoEc.times(null, undefined)).toBe(0)
expect(NPNoEc.times(undefined, null)).toBe(0)
expect(NPNoEc.times(undefined, 0)).toBe(0)
expect(NPNoEc.times(0, undefined)).toBe(0)
for (let i = 0; i < 1; i = NP.plus(i, 0.01)) {
const num = NPNoEc.times(i, 100)
expect(num).not.toBeUndefined()
expect(num).not.toBeNull()
// expect((i * 100).toString().length).toBeLessThan(8)
expect((num).toString().length).toBeLessThan(8)
}
});