You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用toFixed方法时如何避免数字被四舍五入?

如何实现小数不四舍五入保留两位小数?

下面提供几种实用方案,解决toFixed(2)自动四舍五入的问题:

方法一:数学截断法

通过放大数值、向下取整再缩小的逻辑实现截断,核心用Math.floor替代四舍五入:

const num = 19.528;
const truncated = Math.floor(num * 100) / 100;
console.log(truncated); // 输出 19.52

注意:JavaScript浮点数基于二进制存储,部分小数会存在精度偏移(比如0.19999999999999998),极端场景可结合字符串处理或精确计算库优化。

方法二:字符串截取法

直接操作字符串截取指定小数位数,适合需要固定格式字符串输出的场景:

function truncateToTwoDecimals(num) {
  const str = num.toString();
  const dotIndex = str.indexOf('.');
  // 处理整数情况
  if (dotIndex === -1) {
    return `${str}.00`;
  }
  // 截取整数部分+前两位小数,不足补0
  const integerPart = str.slice(0, dotIndex);
  const decimalPart = str.slice(dotIndex + 1, dotIndex + 3).padEnd(2, '0');
  return `${integerPart}.${decimalPart}`;
}

// 测试示例
console.log(truncateToTwoDecimals(19.528)); // "19.52"
console.log(truncateToTwoDecimals(20)); // "20.00"
console.log(truncateToTwoDecimals(19.5)); // "19.50"

若需返回数字类型,在外层包裹Number()即可,同样需注意浮点数精度问题。

方法三:位运算快速截断(仅适用于正数)

对于正数,可用位运算~~快速取整,效果与Math.floor一致,代码更简洁:

const num = 19.528;
const truncated = ~~(num * 100) / 100;
console.log(truncated); // 19.52

注意:位运算会将数值转为32位整数,因此数值不能超过2^31-1,否则会出现溢出。

内容的提问来源于stack exchange,提问作者Kimbo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 20:01:14