掌握 JavaScript 中的数字方法
javascript 中的数字方法
javascript 提供了多种内置方法来有效地处理数字。这些方法允许您执行格式化、舍入、解析和验证数字等操作。
1.转换数字
a. tostring()
将数字转换为字符串。
1 2 3 4 5 | const num = 123; console.log(num.tostring()); // output: "123" console.log((456).tostring()); // output: "456" |
b.固定(数字)
格式化具有固定小数位数的数字。
1 2 3 4 5 | const num = 3.14159; console.log(num.tofixed(2)); // output: "3.14" console.log(num.tofixed(4)); // output: "3.1416" |
c.指数(数字)
返回指数表示法的数字。
1
2const num = 12345;
console.log(num.toexponential(2)); // output: "1.23e+4"
d. toprecision(数字)
将数字格式化为指定的总长度(包括小数)。
1 2 3 | const num = 12345; console.log(num.toexponential(2)); // output: "1.23e+4" |
2.解析和验证数字
a. parseint(字符串, 基数)
将字符串解析为整数。
1 2 3 | console.log(parseint( "123" )); // output: 123 console.log(parseint( "101" , 2)); // output: 5 (binary to decimal) |
b. parsefloat(字符串)
将字符串解析为浮点数。
1 2 3 | console.log(parsefloat( "3.14" )); // output: 3.14 console.log(parsefloat( "123abc" )); // output: 123 |
检查值是否为整数。
1 2 3 | console.log(number.isinteger(123)); // output: true console.log(number.isinteger(3.14)); // output: false |
检查一个值是否是有限数。
1 2 3 | console.log(number.isfinite(123)); // output: true console.log(number.isfinite(infinity)); // output: false |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通