JavaScript 中将带逗号的字符串解析为数字
JavaScript 中要将带逗号的字符串解析为数字:
-
使用
replace()
方法从字符串中删除所有逗号。 -
replace()
方法将返回一个不包含逗号的新字符串。 - 将字符串转换为数字。
const str = '12,000,000.50';
const num = parseFloat(str.replace(/,/g, ''));
console.log(num); // 👉️ 123000000.5
我们使用 String.replace
方法从字符串中删除所有逗号。
该方法采用的第一个参数是正则表达式,第二个参数是正则表达式的每个匹配项的替换。
正斜杠 //
标记正则表达式的开始和结束。
我们只匹配正则表达式中的一个逗号。
const str = '12,000,000.50';
const num = parseFloat(str.replace(/,/g, ''));
console.log(num); // 👉️ 123000000.5
我们使用了
g
(全局)标志,因为我们想要匹配字符串中所有出现的逗号,而不仅仅是第一次出现的逗号。
如果我们在阅读正则表达式时需要帮助,请查看我们的正则表达式教程 。
我们想删除所有逗号,所以我们用一个空字符串替换每个逗号。
最后一步是用结果调用 parseFloat
函数。
parseFloat
函数解析提供的字符串并返回一个浮点数。
如果 parseFloat
函数无法将字符串转换为数字,因为字符串包含非数字字符,则该方法返回 NaN(不是数字)。
下面是一些使用 parseFloat
函数的例子。
console.log(parseFloat('100')); // 👉️ 100
console.log(parseFloat('100.5')); // 👉️ 100.5
console.log(parseFloat(10.5)); // 👉️ 10.5
console.log(parseFloat('a123')); //👉️ NaN
如果希望避免使用正则表达式,请使用 String.replaceAll
方法。
const str = '12,000,000.50';
const num = parseFloat(str.replaceAll(',', ''));
console.log(num); // 👉️ 123000000.5
此代码片段实现了相同的结果。 但是,我们向 replaceAll()
方法传递了一个字符串而不是正则表达式。
第二个参数是每个匹配项的替换。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。