JS 浮点数转整数的方法

拼搏现实的明天。 2023-07-19 04:48 83阅读 0赞

1. parseInt

概念:以第二个参数为基数来解析第一个参数字符串,通常用来做十进制的取整(省略小数)如:parseInt(2.7) //结果为2

特点:接收两个参数parseInt(string,radix)

[‘1’,’2’,’3’].map(parseInt)结果

result:[1, NaN, NaN]

[‘1’,’2’,’3’].map(parseInt) 就是将字符串1,2,3作为元素;0,1,2作为下标分别调用 parseInt 函数。即分别求出 parseInt(‘1’,0), parseInt(‘2’,1), parseInt(‘3’,2)的结果

2.位运算

1 console.log("123.45"| 0)``//123

2 console.log(123.45 | 0)``//123

3 console.log(123.45 ^ 0)``//123

4 console.log(~~123.45)``//123

浮点数是不支持位运算的,所以会先把1.1转成整数1再进行位运算,就好像是对浮点数向下求整。所以1|0的结果就是1

删除最后一个数字

按位或运算符还可以用于从整数的末尾删除任意数量的数字。这意味着我们不需要使用这样的代码来在类型之间进行转换。

  1. let str = "1553";
  2. Number(str.substring(0, str.length - 1));

相反,按位或运算符可以这样写:

  1. console.log(1553 / 10 | 0) // Result: 155
  2. console.log(1553 / 100 | 0) // Result: 15
  3. console.log(1553 / 1000 | 0) // Result: 1

3. Math

  • Math.round:四舍五入;Math.round(3.6) == 4
  • Math.ceil:向上取整;Math.ceil(3.4) == 4
  • Math.floor:向下取整;Math.floor(3.6) == 3

发表评论

表情:
评论列表 (有 0 条评论,83人围观)

还没有评论,来说两句吧...

相关阅读

    相关 js乘法出现点数

    说明 众所周知,js在计算浮点数时候,结果可能会不准确。比如:(在chrome中的运算结果)  2.2 + 2.1 = 4.300000000000001  2.2

    相关 点数--定点数

    知识准备: 1. 输出浮点数的十六进制形式?(利用指针输出) 将浮点数指针-转换成-整型指针,以十六进制的格式输出指针内容。 示例程序: include