YouTip LogoYouTip

Jsref Trunc

## JavaScript Math.trunc() Method The `Math.trunc()` method is a built-in JavaScript function used to return the integer part of a number by removing any fractional (decimal) digits. Unlike other rounding methods, `Math.trunc()` does not round the number up or down; it simply truncates (cuts off) the decimal point and everything to the right of it. --- ## Syntax ```javascript Math.trunc(x) ``` ### Parameter Values | Parameter | Description | | :--- | :--- | | `x` | Required. A number or any value that can be converted into a numeric value. | ### Return Value | Type | Description | | :--- | :--- | | `Number` | The integer part of the given number. Returns `NaN` if the argument cannot be converted to a number. | --- ## Browser Support `Math.trunc()` is an ES6 (ECMAScript 2015) feature and is fully supported in all modern browsers: | Chrome | Edge | Firefox | Safari | Opera | | :---: | :---: | :---: | :---: | :---: | | Yes | Yes | Yes | Yes | Yes | --- ## Basic Examples ### Example 1: Truncating Positive Numbers ```javascript let result = Math.trunc(8.76); console.log(result); // Output: 8 ``` ### Example 2: Truncating Negative Numbers ```javascript let result = Math.trunc(-8.76); console.log(result); // Output: -8 ``` --- ## Comprehensive Examples The following examples demonstrate how `Math.trunc()` behaves with different types of inputs, including positive numbers, negative numbers, numeric strings, and non-numeric values: ```javascript Math.trunc(13.37); // Returns 13 Math.trunc(42.84); // Returns 42 Math.trunc(0.123); // Returns 0 Math.trunc(-0.123); // Returns -0 Math.trunc("-1.123"); // Returns -1 (string is implicitly converted to a number) Math.trunc(NaN); // Returns NaN Math.trunc("foo"); // Returns NaN (string cannot be converted to a number) Math.trunc(); // Returns NaN (undefined argument) ``` --- ## Technical Considerations & Comparisons ### `Math.trunc()` vs. Other Rounding Methods It is important to understand how `Math.trunc()` differs from other `Math` methods like `Math.floor()`, `Math.ceil()`, and `Math.round()`β€”especially when dealing with negative numbers. | Input | `Math.trunc()` (Truncates) | `Math.floor()` (Rounds Down) | `Math.ceil()` (Rounds Up) | `Math.round()` (Rounds to Nearest) | | :--- | :---: | :---: | :---: | :---: | | **`3.7`** | `3` | `3` | `4` | `4` | | **`3.2`** | `3` | `3` | `4` | `3` | | **`-3.2`** | `-3` | `-4` | `-3` | `-3` | | **`-3.7`** | `-3` | `-4` | `-3` | `-4` | ### Polyfill for Older Environments (Pre-ES6) If you need to support legacy environments (like Internet Explorer) that do not support `Math.trunc()`, you can use the following polyfill: ```javascript if (!Math.trunc) { Math.trunc = function(v) { v = Number(v); return v < 0 ? Math.ceil(v) : Math.floor(v); }; } ```
← Prop Element ScrollleftJsref Class Super β†’