javascript怎么将小数转换为整数

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>);

输出结果:

10
10
34
60
40
NaN

10
10
8
16
16

方法2:两次取反

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

输出结果:

4

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

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

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

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

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

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

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

Math.round():四舍五入。

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

【推荐学习:javascript高级教程

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...