JavaScript 中 Math.trunc() 方法的重要性是什么?

javascriptobject oriented programmingfront end technology

Math.trunc()

Math.floor()Math.ceil()Math.round() 不同,Math.trunc() 方法会删除 小数部分,只给出 整数部分。它不关心将数字四舍五入为最接近的整数。它甚至不会注意到该值是正数还是负数。它的功能只是将小数部分切碎。

语法

Math.trunc(x);

参数 - Math.trunc() 以数字作为参数并截断小数部分。

在下面的例子中,Math.trunc() 方法截断了所提供正数的小数值。

示例

<html>
<body>
<script>
   var val1 = Math.trunc("1.414");
   var val2 = Math.trunc("0.49");
   var val3 = Math.trunc("8.9");
   document.write(val1);
   document.write("</br>");
   document.write(val2);
   document.write("</br>");
   document.write(val3);
</script>
</body>
</html>

输出

1
0
8

在以下 Math.trunc()  函数中,截断了负数的小数值,并在输出中显示其整数值。

示例

<html>
<body>
<script>
   var val1 = Math.trunc("-1.414");
   var val2 = Math.trunc("-0.49");
   var val3 = Math.trunc("-8.9");
   document.write(val1);
   document.write("</br>");
   document.write(val2);
   document.write("</br>");
   document.write(val3);
</script>
</body>
</html>

输出

-1
0
-8

相关文章