基本信息
文件名称:JavaScript如何删除小数点后的数字.docx
文件大小:15.44 KB
总页数:2 页
更新时间:2025-05-21
总字数:约1.21千字
文档摘要

JavaScript如何删除小数点后的数字

使用Math.trunc()函数删除小数点后的数字,例如Math.trunc(1.37)。Math.trunc()函数删除小数位并返回数字的整数部分。

constnum=124.567;

constremoveDecimal=Math.trunc(num);//124

console.log(removeDecimal);

constroundDown=Math.floor(num);//124

console.log(roundDown);

constroundNearestInteger=Math.round(num);//125

console.log(roundNearestInteger);

constroundUp=Math.ceil(num);

console.log(roundUp);//125

我们的第一个示例使用Math.trunc函数。

该函数不会以任何方式对数字进行四舍五入,它只是移除小数部分并返回整数。

看下面的示例

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

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

console.log(Math.trunc(5.35));//5

下一个可能的情况是通过向下舍入来删除小数点后的数字。使用Math.floor函数。

该函数返回小于或等于提供的数字的最大整数。这里有些例子。

console.log(Math.floor(-1.37));//-2

console.log(Math.floor(2.6));//2

console.log(Math.floor(5.35));//5

下一个示例显示如何使用Math.round函数将数字四舍五入到最接近的整数。这里有些例子。

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

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

console.log(Math.round(5.49));//5

最后一个示例显示了如何使用Math.ceil函数通过四舍五入来删除小数点后的数字。

Math.ceil函数总是向上进入一个数字。这里有些例子。

console.log(Math.ceil(-1.99));//-1

console.log(Math.ceil(2.01));//3

console.log(Math.ceil(5.49));//6

如果您想简单地删除小数点后的数字,而不以任何方式进行四舍五入,请使用Math.trunc函数。