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

如何在JavaScript中将带千分位的1,800.00转换为整数1800?

解决带千分位逗号的数值字符串转数字的问题

我懂你碰到的这个坑——Number()函数根本认不出带千分位逗号的字符串,所以直接转换肯定会返回NaN,毕竟逗号不是JavaScript合法的数值字符嘛。下面给你几个实用的解决方案:

方法一:移除逗号后直接转换

这是最直接简单的方式,先把字符串里的逗号全部去掉,再转成数字,最后按需取整:

const numStr = "1,100.00";
// 全局移除所有逗号
const cleanedString = numStr.replace(/,/g, '');
// 转成浮点数
const floatNum = Number(cleanedString);
// 转成整数(如果需要的话)
const integerNum = Math.floor(floatNum);
console.log(integerNum); // 输出 1100

如果你的字符串前后有空格,还可以先加个trim()处理:numStr.trim().replace(/,/g, '')。

方法二:用Intl.NumberFormat解析(更健壮)

如果之后可能要处理不同地区的数值格式(比如有些地区用.做千分位),用Intl.NumberFormat的解析器会更靠谱,针对你的场景指定en-US地区即可:

const numStr = "1,800.00";
const numberParser = new Intl.NumberFormat('en-US');
const parsedNum = numberParser.parse(numStr);
// 转成整数
const integerNum = Math.floor(parsedNum);
console.log(integerNum); // 输出 1800

这个方法返回的是浮点数,所以需要再处理成整数。

方法三:结合parseFloat和替换

用parseFloat直接处理移除逗号后的字符串,再转整数:

const numStr = "1,100.00";
const floatNum = parseFloat(numStr.replace(/,/g, ''));
const integerNum = parseInt(floatNum, 10);
console.log(integerNum); // 输出 1100

如果需要四舍五入的话,把parseInt换成Math.round()就可以了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:13:44