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 来判断数字的基数。
立即学习“Java免费学习笔记(深入)”;
当忽略参数 radix , JavaScript 默认数字的基数如下:
如果 string 以 “0x” 开头,parseInt() 会把 string 的其余部分解析为十六进制的整数。
如果 string 以 0 开头,那么 ECMAScript v3 允许 parseInt() 的一个实现把其后的字符解析为八进制或十六进制的数字。
如果 string 以 1 ~ 9 的数字开头,parseInt() 将把它解析为十进制的整数。
示例:使用 parseInt() 来解析不同的字符串
document.write(parseInt("10") + "
");document.write(parseInt("10.33") + "
");document.write(parseInt("34 45 66") + "
");document.write(parseInt(" 60 ") + "
");document.write(parseInt("40 years") + "
");document.write(parseInt("He was 40") + "
"); document.write("
");document.write(parseInt("10",10)+ "
");document.write(parseInt("010")+ "
");document.write(parseInt("10",8)+ "
");document.write(parseInt("0x10")+ "
");document.write(parseInt("10",16)+ "
");
登录后复制
输出结果:
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怎么将小数转换为整数的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2708189.html