createRound
源码
/**
* 创建一个像 round 类似函数。
*
* @private
* @param {string} methodName 使用 Math中对应的 rounding 方法 ceil/floor/round。
* @returns {Function} 返回新的 round 函数。
*/
function createRound(methodName) {
const func = Math[methodName];
return (number, precision) => {
precision = precision == null ? 0 : precision >= 0 ? Math.min(precision, 292) : Math.max(precision, -292);
if (precision) {
// 使用科学计数法移位以避免浮点问题。
// 查看 [MDN](https://mdn.io/round#Examples) 获取更多详情。
let pair = `${number}e`.split('e');
const value = func(`${pair[0]}e${+pair[1] + precision}`);
pair = `${value}e`.split('e');
return +`${pair[0]}e${+pair[1] - precision}`;
}
return func(number);
};
}原理
极限精度值 1e292/1e-292 (TODO)
科学计数法移位计算
相关链接
Last updated