js怎么取整数


本文摘自PHP中文网,作者藏色散人,侵删。

js取整数的方法:1、通过“Math.trunc()”方法去除数字的小数部分,保留整数部分;2、通过“Math.round()”方法返回一个数字四舍五入后的整数部分;3、通过“Math.ceil()”方法实现向上取整等等。

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

JavaScript进行数值取整:

一、Math.trunc()

1、定义

Math.trunc()方法去除数字的小数部分,保留整数部分。

2、语法

1

Math.trunc(value)

3、示例

1

2

3

4

5

6

7

console.log(Math.trunc(2.01)); // 2

console.log(Math.trunc(2.9)); // 2

console.log(Math.trunc('0.22')); // 0

console.log(Math.trunc(-1.22)); // -1

console.log(Math.trunc(-1.56)); // -1

console.log(Math.trunc(true)); // 1

console.log(Math.trunc(undefined)); // NaN

二、Math.round()

1.定义

Math.round()方法返回一个数字四舍五入后的整数部分。

2、语法

1

Math.round(value)

3、示例

1

2

3

4

5

6

7

console.log(Math.round(2.01)); // 2

console.log(Math.round(2.9)); // 3

console.log(Math.round('0.22')); // 0

console.log(Math.round(-1.22)); // -1

console.log(Math.round(-1.56)); // -2

console.log(Math.round(true)); // 1

console.log(Math.round(undefined)); // NaN

三、Math.ceil()

阅读剩余部分

相关阅读 >>

如何利用js对css样式进行更改

怎么获取json的key

js (javascript)加密算法库 crypto-js 简介

js实现加载时锁定html页面元素的方法

三种js数组去重的简洁方案

js控制输入框只允许输入小数

js代表什么

js面向对象编程

javascript 和 dart 的区别

jquery怎么写ajax

更多相关阅读请进入《js》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...