JavaScript Math.trunc()
Method: Getting the Integer Part of a Number
The Math.trunc()
method in JavaScript is a built-in function that returns the integer part of a number by removing any fractional digits. It’s a straightforward way to get the integer portion without rounding, making it useful for various mathematical and programming tasks. This guide provides a deep dive into the Math.trunc()
method, including its syntax, usage, and practical examples.
What is Math.trunc()
?
The Math.trunc()
method removes the fractional part (the digits following the decimal point) of a number, effectively truncating the number to its integer component. Unlike Math.floor()
or Math.ceil()
, Math.trunc()
doesn’t round the number up or down; it simply cuts off the decimal part.
Syntax
The syntax for the Math.trunc()
method is simple:
Math.trunc(x);
Here, x
is the number you want to truncate.
Parameters
x
: A number or an expression that evaluates to a number.
Return Value
The Math.trunc()
method returns:
- The integer part of the given number.
NaN
if the argument is not a number or cannot be converted to a number.+0
if the argument is+0
.-0
if the argument is-0
.
Basic Usage Examples
Let’s start with some basic examples to illustrate how Math.trunc()
works.
Example 1: Truncating Positive Numbers
let positiveNumber = 42.84;
let truncatedPositive = Math.trunc(positiveNumber);
console.log(truncatedPositive); // Output: 42
In this example, Math.trunc()
removes the fractional part .84
from 42.84
, resulting in 42
.
Example 2: Truncating Negative Numbers
let negativeNumber = -42.84;
let truncatedNegative = Math.trunc(negativeNumber);
console.log(truncatedNegative); // Output: -42
Here, Math.trunc()
removes the fractional part .84
from -42.84
, resulting in -42
. Note that it doesn’t round towards zero; it simply truncates.
Example 3: Truncating Zero
let zeroNumber = 0.0;
let truncatedZero = Math.trunc(zeroNumber);
console.log(truncatedZero); // Output: 0
The Math.trunc()
of 0.0
is 0
.
Example 4: Truncating Non-Numeric Values
If the argument is not a number or cannot be converted to a number, Math.trunc()
returns NaN
.
let nonNumericValue = "hello";
let truncatedNonNumeric = Math.trunc(nonNumericValue);
console.log(truncatedNonNumeric); // Output: NaN
Advanced Usage and Practical Examples
Let’s explore more advanced scenarios where Math.trunc()
can be useful.
Example 5: Handling Different Number Types
Math.trunc()
works with various numeric types, including integers, floating-point numbers, and numbers represented as strings.
let integerValue = 123;
let floatStringValue = "45.67";
let truncatedInteger = Math.trunc(integerValue);
let truncatedFloatString = Math.trunc(floatStringValue);
console.log(truncatedInteger); // Output: 123
console.log(truncatedFloatString); // Output: 45
Example 6: Using Math.trunc()
with Expressions
Math.trunc()
can be used with mathematical expressions.
let expressionResult = 100 / 3; // Approximately 33.333...
let truncatedExpression = Math.trunc(expressionResult);
console.log(truncatedExpression); // Output: 33
Example 7: Math.trunc()
in Financial Calculations
Math.trunc()
can be useful in financial calculations where you need to ensure values are integers, such as counting whole units of currency.
function calculateWholeUnits(totalAmount, unitPrice) {
let numberOfUnits = totalAmount / unitPrice;
return Math.trunc(numberOfUnits);
}
let totalAmountAvailable = 100;
let pricePerUnit = 7.5;
let wholeUnits = calculateWholeUnits(totalAmountAvailable, pricePerUnit);
console.log(
`You can buy ${wholeUnits} whole units with ${totalAmountAvailable} available.`
); // Output: You can buy 13 whole units with 100 available.
Example 8: Using Math.trunc()
with Canvas API
While Math.trunc()
isn’t directly related to the Canvas API, you might use it when calculating coordinates or sizes that need to be integers.
<canvas id="canvasTrunc" width="200" height="100"></canvas>
<script>
const canvasTrunc = document.getElementById("canvasTrunc");
const ctxTrunc = canvasTrunc.getContext("2d");
function drawGrid(ctx, cellSize) {
for (let x = 0; x < ctx.canvas.width; x += cellSize) {
for (let y = 0; y < ctx.canvas.height; y += cellSize) {
ctx.strokeRect(Math.trunc(x), Math.trunc(y), cellSize, cellSize);
}
}
}
ctxTrunc.strokeStyle = "lightgrey";
drawGrid(ctxTrunc, 20.5); // Intentionally using a non-integer value
</script>
In this example, we use Math.trunc()
to ensure that the grid lines are drawn at integer coordinates, which can help avoid anti-aliasing artifacts that might occur with non-integer coordinates.
Example 9: Using Math.trunc()
in Data Processing
When processing data, you might need to truncate values to ensure they fit within a specific range or format.
function processData(value) {
let truncatedValue = Math.trunc(value);
if (truncatedValue > 100) {
return 100; // Limit to maximum value
}
return truncatedValue;
}
let dataValues = [50.5, 120.7, 75.3, 99.9];
let processedData = dataValues.map(processData);
console.log(processedData); // Output: [50, 100, 75, 99]
When to Use Math.trunc()
- Removing Decimal Parts: Use
Math.trunc()
when you need to remove the fractional part of a number without rounding. - Financial Calculations: When dealing with whole units of currency or items.
- Data Processing: When ensuring values are integers or within a specific range.
- Avoiding Anti-Aliasing: In graphics and canvas applications, to ensure elements are drawn at integer coordinates.
Alternatives to Math.trunc()
Math.floor()
: Rounds a number down to the nearest integer.Math.ceil()
: Rounds a number up to the nearest integer.Math.round()
: Rounds a number to the nearest integer.- Bitwise Operators (
| 0
,~~
): Can be used for truncating numbers, but be cautious as they work differently with negative numbers and large numbers.
Browser Support
The Math.trunc()
method is supported by all modern browsers.
Browser | Version |
---|---|
Chrome | Not Available |
Edge | Not Available |
Firefox | Not Available |
Safari | Not Available |
Opera | Not Available |
IE | Not Available |
Conclusion
The Math.trunc()
method is a simple yet powerful tool for obtaining the integer part of a number in JavaScript. Whether you’re performing financial calculations, processing data, or working with graphics, Math.trunc()
provides a straightforward way to remove the decimal portion without rounding. Understanding its usage and practical applications can help you write cleaner and more efficient code. 🚀