
When you need to strip off the decimal part of a number without rounding, Math.trunc is your go-to tool. Unlike Math.floor or Math.ceil, which round numbers down or up, Math.trunc simply chops off the fractional portion, leaving the integer part exactly as it appears before the decimal point.
This behavior is simpler but often overlooked. For positive numbers, it behaves like Math.floor, but for negative numbers, it acts differently. Where Math.floor(-3.7) yields -4, Math.trunc(-3.7) returns -3, because it doesn’t round down; it just truncates.
Here’s a quick example to see the difference in action:
console.log(Math.trunc(5.9)); // 5 console.log(Math.trunc(-5.9)); // -5 console.log(Math.floor(5.9)); // 5 console.log(Math.floor(-5.9)); // -6
The key is to understand what “truncation” means in this context: simply removing the decimal part, regardless of the sign. That’s especially useful when you care about the integer portion without biasing the value by rounding.
One subtlety is that Math.trunc treats the number as a floating-point value and directly truncates it. It doesn’t convert it to a string or use any form of parsing. This makes it both efficient and predictable, unlike some other methods that rely on string manipulation.
It’s worth noting that Math.trunc was introduced in ES6, so in older environments you might have to polyfill it or use alternative approaches. A simple polyfill looks like this:
if (!Math.trunc) {
Math.trunc = function(v) {
return v < 0 ? Math.ceil(v) : Math.floor(v);
};
}
This mimics the truncation behavior by combining Math.floor and Math.ceil depending on the sign of the value, showing again how truncation differs from flooring or ceiling.
In practice, Math.trunc shines when you want to isolate the integer component in calculations where rounding could introduce errors or unwanted bias. For example, when dealing with pixel values extracted from floating-point calculations, truncation preserves the raw integer coordinate instead of nudging it up or down.
Another arena where truncation is useful is in financial calculations where you want to discard fractional cents temporarily without rounding them, or in cases where the fractional part represents noise or imprecision that should be ignored rather than rounded into the integer result.
Because it simply cuts off the fraction, Math.trunc is also helpful in algorithms that rely on integer division behavior, especially when porting code from languages like C or Java that truncate by default when dividing integers.
To sum up, Math.trunc is a precise tool that does one thing well: remove the decimal part of a number without rounding. It’s subtle, but understanding when to use it instead of floor or ceil can save you from bugs that arise from unintended rounding behavior.
Imagine you’re writing a function that takes a floating-point number representing a user’s progress through a task, where the integer part counts completed steps and the decimal is progress on the current step. Using Math.trunc helps you cleanly separate these two:
function getCompletedSteps(progress) {
return Math.trunc(progress);
}
function getCurrentStepProgress(progress) {
return progress - Math.trunc(progress);
}
console.log(getCompletedSteps(3.7)); // 3
console.log(getCurrentStepProgress(3.7)); // 0.7
This separation is elegant and avoids any rounding that could skew the interpretation of progress.
One could argue that Math.trunc is the most “honest” integer extractor—no rounding, no bias, just the integer part as it appears. This honesty simplifies reasoning about numbers, especially when precise integer extraction is critical.
The function returns the integer part in the form of a Number type, which can still represent very large integers but always respects JavaScript’s numerical precision limits. If you feed Math.trunc a non-numeric value, it returns NaN, so it’s robust but you should still validate inputs.
For example:
console.log(Math.trunc("123.456")); // 123
console.log(Math.trunc("abc")); // NaN
Because Math.trunc coerces the argument to a number before truncation, it can be used flexibly but also requires some care when dealing with user input or untrusted data.
Despite its simplicity, Math.trunc is a fundamental tool worth knowing well, especially for anyone dealing with number manipulation beyond simple rounding tasks. It fills a niche that other Math methods don’t quite cover elegantly, and once you get into the habit of using it appropriately, it can make your code clearer and more correct.
Now let’s move on to how Math.trunc stacks up against other ways of chopping numbers down to integers, and where it fits in the toolbox compared to their behavior and quirks.
LK 6 Pack for Apple Watch Series 11/ Series 10 Screen Protector 42mm - Anti-Scratch, Self-Healing Soft TPU Screen Protector for Apple Watch 42mm, Bubble Free, HD Transparent, Touch Sensitive
Now retrieving the price.
(as of June 12, 2026 00:33 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Comparing Math.trunc with other number truncation methods
When comparing Math.trunc to other truncation methods, it’s essential to consider the context and specific needs of your application. Besides Math.floor and Math.ceil, there are other techniques programmers often employ, like bitwise operators or string manipulation, to achieve similar results. However, these alternatives can introduce complexity or unexpected behavior.
One common alternative is using the bitwise OR operator, which effectively truncates the decimal portion of a number by converting it to a 32-bit integer. Here’s how that looks:
let num = 5.9; let truncated = num | 0; // 5 let negativeNum = -5.9; let negativeTruncated = negativeNum | 0; // -5
This method is concise and performs well, but it has its quirks. It only works with 32-bit integers, so if you go beyond that range, you’ll run into issues. It also behaves differently with non-numeric values, returning 0 if the value is not a number, which might not be the desired behavior.
Another alternative is to convert the number to a string and then back to a number after slicing off the decimal part:
function truncateUsingString(num) {
return Number(num.toString().split('.')[0]);
}
This technique is less efficient and often less readable, as it introduces unnecessary complexity and potential pitfalls, such as handling edge cases where the input is not a valid number. It also doesn’t handle negative numbers correctly without additional logic.
In contrast, Math.trunc provides a clean, simpler approach without the drawbacks of bitwise operations or string manipulation. It’s designed to handle both positive and negative numbers intuitively. For instance, consider how it performs with various inputs:
console.log(Math.trunc(7.9)); // 7 console.log(Math.trunc(-7.9)); // -7 console.log(Math.trunc(0)); // 0 console.log(Math.trunc(-0)); // 0
This predictability makes Math.trunc a safer option in many scenarios. It directly addresses the need for truncation without introducing other variables that could lead to confusion or errors.
Moreover, there are situations where truncation is part of a larger calculation. For instance, when calculating the index of an array based on a floating-point value, using Math.trunc ensures that you always get a valid array index without the risk of exceeding the bounds or getting a negative index from rounding:
function getArrayIndex(value, arrayLength) {
return Math.trunc(value) % arrayLength;
}
This method keeps your code safe and efficient. When you need to ensure that you’re working with integers derived from floating-point numbers, Math.trunc should be your first choice.
In real-world applications, the choice of truncation method can have significant implications, especially when performance and accuracy are critical. Using Math.trunc not only clarifies intent but also minimizes the risk of unintended consequences that could arise from using less direct methods.
Furthermore, with the rise of TypeScript and stricter type-checking, using Math.trunc aligns well with a more robust coding style that emphasizes clarity and correctness. It can be particularly useful in scenarios involving numerical calculations where the distinction between truncation and rounding matters significantly.
Ultimately, while there are multiple ways to truncate numbers in JavaScript, Math.trunc stands out for its clarity, simplicity, and correctness. It’s a tool that every JavaScript developer should have in their arsenal, especially when working on applications that require precise numerical operations.
Practical examples of using Math.trunc in real-world applications
In real-world applications, the utility of Math.trunc can be seen in various domains, from gaming to financial modeling. Consider a scenario in game development where you need to manage player scores that can be represented as floating-point numbers. You might want to display the integer part of the score without rounding it up, ensuring that players see their exact score at any moment:
function displayScore(score) {
return Math.trunc(score);
}
console.log(displayScore(99.99)); // 99
console.log(displayScore(150.5)); // 150
This approach guarantees that players are aware of their true score without any rounding that could mislead them about their performance.
Another practical example is in the sphere of data processing. When aggregating data points that may include floating-point representations of measurements, such as temperature readings, you might need to truncate these values for reporting purposes. Here’s how that might look:
function aggregateTemperatures(temperatures) {
return temperatures.map(temp => Math.trunc(temp));
}
const readings = [78.9, 82.3, 79.5, 80.1];
console.log(aggregateTemperatures(readings)); // [78, 82, 79, 80]
This method effectively prepares the data for visualization or storage, ensuring that the fractional parts do not introduce noise into the aggregated results.
Furthermore, Math.trunc can be particularly useful in scenarios involving pagination or UI components that require integer values for display purposes. For instance, when calculating how many items to show per page based on a floating-point user input:
function calculateItemsPerPage(input) {
return Math.trunc(input);
}
console.log(calculateItemsPerPage(10.7)); // 10
This function ensures that the number of items displayed per page is always a whole number, preventing any unexpected behavior in the user interface.
In financial applications, where precision is paramount, using Math.trunc allows developers to handle currency values effectively without introducing rounding errors. For example, when calculating discounts or taxes on prices:
function calculateDiscountedPrice(price, discount) {
const discountedPrice = price - (price * discount);
return Math.trunc(discountedPrice);
}
console.log(calculateDiscountedPrice(99.99, 0.15)); // 84
Here, truncation ensures that the final price reflects the exact discount without rounding it up, which could mislead customers.
Moreover, in analytics or reporting systems, where data integrity is critical, Math.trunc helps maintain the accuracy of reported figures by removing unnecessary decimal places that may not be relevant to the analysis:
function reportMetric(value) {
return Math.trunc(value);
}
console.log(reportMetric(1234.56789)); // 1234
This simple function can be used to standardize metrics across reports, ensuring that all values are presented in a consistent format.
In summary, the versatility of Math.trunc in these examples illustrates its role as a fundamental tool in the JavaScript developer’s toolkit. By applying it in various contexts—whether in gaming, data processing, UI development, or financial applications—you can achieve clarity and precision in your numerical operations, enhancing the overall quality of your code.
