JavaScript Math trunc()

trunc() 方法会截断(缩短)数字并返回其整数部分。

示例

let number = Math.trunc("420.56");
console.log(number); 

// Output: 420

trunc() 语法

Math.trunc() 方法的语法是:

Math.trunc(number)

在这里,trunc() 是一个静态方法。因此,我们使用类名 Math 来访问该方法。


trunc() 参数

trunc() 方法接受一个参数:

  • number - 需要截断(缩短为整数)的值

trunc() 返回值

trunc() 方法返回:

  • number 的整数部分
  • 对于非数字参数,返回 NaN(非数字)。

示例 1:JavaScript Math.trunc()

// trunc() with a negative number let number1 = Math.trunc(-50.456);
console.log(number1);
// trunc() with a positive number let number2 = Math.trunc(18.645);
console.log(number2); // Output: // -50 // 18

在这里,Math.trunc() 返回:

  • 对于负数 -50.45627,返回 -50
  • 对于正数 18.645,返回 18

注意: trunc() 方法不会对数字进行四舍五入,它只是删除小数点后的数字并返回整数部分。


示例 2:JavaScript Math.trunc() 与数字字符串

// trunc() with a numeric string let number2 = Math.trunc("15.645");
console.log(number2); //Output:15

在上面的示例中,Math.trunc("15.645") 会将数字字符串转换为数字并进行截断。


示例 3:JavaScript Math.trunc() 与非数字参数

let string = "Luke";
// trunc() with string argument let value = Math.trunc(string);
console.log(value); // Output: NaN

在上面的示例中,我们将 trunc() 方法与字符串参数 "Luke" 一起使用。这就是为什么我们得到 NaN 作为输出。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战