首页 > 文章列表 > js将小数转为整数的方法

js将小数转为整数的方法

js 小数 整数
307 2022-08-06

1、使用“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)+ "
");

2、使用“~~小数值”语句。

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

3、使用“Math.floor(小数值)”语句。

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

4、使用“Math.ceil(小数值)”语句。

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

5、使用“Math.round(小数值)”语句。

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