您的位置 首页 技术

javascript怎么将小数转换为整数

JS将小数转为整数的方法:1、使用“parseInt(小数值)”语句;2、使用“~~小数值”语句;3、使用“Math.floor(小数值)”语句;4、使用“Math.ceil(小数…

JS将小数转为整数的方法:1、使用“parseInt(小数值)”语句;2、使用“~~小数值”语句;3、使用“Math.floor(小数值)”语句;4、使用“Math.ceil(小数值)”语句;5、使用“Math.round(小数值)”语句。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

方法1:使用 parseInt()

parseInt() 函数可解析一个字符串,并返回一个整数。

当参数 radix 的值为 0,或没有设置该参数时,parseInt() 会根据 string 来判断数字的基数。

当忽略参数 radix , JavaScript 默认数字的基数如下:

  • 如果 string 以 "0x" 开头,parseInt() 会把 string 的其余部分解析为十六进制的整数。

  • 如果 string 以 0 开头,那么 ECMAScript v3 允许 parseInt() 的一个实现把其后的字符解析为八进制或十六进制的数字。

  • 如果 string 以 1 ~ 9 的数字开头,parseInt() 将把它解析为十进制的整数。

示例:使用 parseInt() 来解析不同的字符串

document.write(parseInt("10") + "<br>");document.write(parseInt("10.33") + "<br>");document.write(parseInt("34 45 66") + "<br>");document.write(parseInt(" 60 ") + "<br>");document.write(parseInt("40 years") + "<br>");document.write(parseInt("He was 40") + "<br>"); document.write("<br>");document.write(parseInt("10",10)+ "<br>");document.write(parseInt("010")+ "<br>");document.write(parseInt("10",8)+ "<br>");document.write(parseInt("0x10")+ "<br>");document.write(parseInt("10",16)+ "<br>");

输出结果:

1010346040NaN101081616

方法2:两次取反

var decimal=4;var integer = ~~decimal; // 4 = ~~4.123console.log(integer);

输出结果:

4

方法3:Math.floor()向下取整

Math.floor():返回小于参数值的最大整数。

console.log(Math.floor(2.5));  //2console.log(Math.floor(-2.5));  //-3

方法4:Math.ceil()向上取整

Math.ceil():返回大于参数值的最小整数。

console.log(Math.ceil(2.5));  //3console.log(Math.ceil(-2.5));  //-2

方法5:Math.round()四舍五入

Math.round():四舍五入。

console.log(Math.round(2.5));  //3console.log(Math.round(-2.5));  //-2console.log(Math.round(-2.6));  //-3

【推荐学习:javascript高级教程】

以上就是javascript怎么将小数转换为整数的详细内容,更多请关注24课堂在线网其它相关文章!

本文来自网络,不代表24小时课堂在线立场,转载请注明出处:https://www.24ketang.cn/95904.html

为您推荐

返回顶部