https://math.haozi.me/trunc.html Easy Math for Coder
Activity
benboba commentedon Oct 30, 2020
直接减去自身的模会遇到浮点数精度问题
1.13 - 0.13 = 0.9999999999999999
所以不能直接返回 int,需要一个修补函数,类似这样的:
const fixedFloat = x => {
const [int, decimal] = x.toString().split('.')
if (!decimal) return x;
if (decimal[0] === '0') return +int; // 此处可能遇到另一个坑,就是科学计数法,但如果只是为 trunc 服务,应该是可以的
return +int + 1;
};
haozi commentedon Oct 30, 2020
不过,话说回来,如果用 toString 的话,直接就可以用字符串的方法 trunc 了