迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 中把字符串转换为数字

作者:迹忆客 最近更新:2023/03/09 浏览次数:

我们必须有各种方案来转换数字。例如,从 API 或数据库查询中提取的数据以字符串格式转换为数字。由于对字符串的操作不同,可能有必要将这些字符串转换为数字格式,以便轻松地对其进行算术运算。这里有一些方法可以做到这一点:

Number()Number 构造函数,可用于将其他数据类型转换为数字格式(根据 MDN 文档)。如果输入参数未定义或不能转换为数字,则返回 NaN。例如:

console.log(Number("246"))
console.log(Number("246.5"))
console.log(Number(undefined))
console.log(Number("Hello"))

输出:

246
246.5
NaN
NaN

处理字符串数字的另一种方法是使用 JavaScript 的 parseInt() 方法。parseInt() 有两个参数,一个是需要转换的字符串,另一个是 radix(表示基数)。我们日常生活中处理的大多数数字通常以 10 为基数,这表示一个十进制值。在大多数情况下,我们不需要将基数指定为默认值 10。

console.log(parseInt("123")); 
console.log(parseInt("abc")); 
console.log(parseInt("-123")); 
console.log(parseInt("100.50"));

输出:

123
NaN
-123
100

parseInt("100.50") 返回 100 而不是 100.50,因为它将输入数字转换为整数。因此,在使用 parseInt() 时要注意这一事实。

parseInt() 还可以转换十六进制值以及具有不同基数系统的值,例如二进制系统,八进制系统等。有关更多信息,请查看文档。同样,我们可以使用 parseFloat() 将字符串转换为浮点数。

Math 是 JavaScript 中的内置对象,具有用于复杂数学运算的方法。它适用于数据类型编号。但是,很少使用此内置对象的方法将字符串转换为整数。例如,

console.log(Math.ceil("123"));
console.log(Math.floor("300"));
console.log(Math.abs("450"));

输出:

123
300
450

但是,使用 Math 方法进行转换时会遇到陷阱。对于浮点值,我们无法使用它们,因为它们会将它们转换为整数。因此,我们将丢失该值的小数部分。

console.log(Maths.abs("240.64")) 
console.log(Math.abs("-240.25")) 

输出:

240.64 // The decimal value of .64 is captured here
240.25 // -240.25 is transformed to 240.25

根据我们期望从字符串号中获取的值,最好的选择是使用 Number() 方法。如果只使用整数值,建议使用 parseInt()。明智地使用 JavaScript 中的内置 Math 对象来转换字符串,因为根据我们使用的方法,它可能很棘手。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便