Multiple Methods and Implementation Principles for Removing Decimal Parts from Numbers in JavaScript

Nov 08, 2025 · Programming · 9 views · 7.8

Keywords: JavaScript | Number Processing | Decimal Truncation | Math.trunc | Bitwise Operators

Abstract: This article provides an in-depth exploration of various methods in JavaScript for removing the decimal parts of numbers, including Math.trunc(), Math.floor(), Math.ceil(), Math.round(), and bitwise operators. It analyzes implementation principles, applicable scenarios, platform compatibility, and provides complete code examples with performance comparisons. Special attention is given to floating-point precision issues and 32-bit integer limitations to help developers choose the most suitable solution.

Introduction

In JavaScript development, handling the decimal parts of numbers is a common requirement. Whether for financial calculations, data visualization, or algorithm implementation, precise control over the integer part of numbers is essential. Based on high-scoring Stack Overflow answers and authoritative documentation, this article systematically analyzes various methods for removing decimal parts in JavaScript.

Detailed Analysis of Core Methods

Math.trunc() Method

Math.trunc() is a standard method introduced in ECMAScript 6, specifically designed to truncate the decimal part of a number. Its implementation principle involves directly removing all digits after the decimal point without any rounding.

Example code:

console.log(Math.trunc(3.14));  // Output: 3
console.log(Math.trunc(-3.14)); // Output: -3
console.log(Math.trunc(0.123)); // Output: 0

This method behaves consistently for both positive and negative numbers, simply removing the decimal part. For browser compatibility issues, the following polyfill can be used:

if (!Math.trunc) {
    Math.trunc = function(x) {
        return x < 0 ? Math.ceil(x) : Math.floor(x);
    };
}

Math.floor() Method

The Math.floor() method rounds a number down to the nearest integer. For positive numbers, the effect is the same as Math.trunc(); however, for negative numbers, the behavior differs.

Example code:

console.log(Math.floor(3.14));  // Output: 3
console.log(Math.floor(-3.14)); // Output: -4
console.log(Math.floor(0.123)); // Output: 0

This method rounds negative numbers toward smaller values, so this distinction must be noted when strict truncation of the decimal part is required.

Math.ceil() Method

The Math.ceil() method rounds a number up to the nearest integer. Opposite to Math.floor(), it always rounds toward larger values.

Example code:

console.log(Math.ceil(3.14));  // Output: 4
console.log(Math.ceil(-3.14)); // Output: -3
console.log(Math.ceil(0.123)); // Output: 1

This method is suitable for scenarios requiring upward rounding, such as calculating the number of pages for pagination.

Math.round() Method

The Math.round() method rounds a number to the nearest integer. This is one of the most commonly used rounding methods.

Example code:

console.log(Math.round(3.14));  // Output: 3
console.log(Math.round(3.5));   // Output: 4
console.log(Math.round(-3.14)); // Output: -3
console.log(Math.round(-3.5));  // Output: -3

It is important to note that rounding in JavaScript follows the "banker's rounding" method, where numbers exactly in the middle are rounded to the nearest even number.

Bitwise Operator Method

Using bitwise operators is another effective method for removing decimal parts, with excellent platform compatibility.

Example code:

console.log(3.14 | 0);  // Output: 3
console.log(-3.14 | 0); // Output: -3
console.log(0.123 | 0); // Output: 0

Bitwise operators work by treating the operand as a 32-bit signed integer, automatically truncating the decimal part. However, this method has significant limitations: it can only handle numbers within the 32-bit range (-2,147,483,648 to 2,147,483,647), and numbers outside this range will produce incorrect results.

Other available bitwise operators include:

console.log(3.14 >> 0);   // Output: 3
console.log(~~3.14);      // Output: 3
console.log(3.14 << 0);   // Output: 3

Performance Comparison and Analysis

In practical applications, the performance of different methods varies. Benchmark tests reveal:

Example performance test code:

function benchmark() {
    const iterations = 1000000;
    let start, end;
    
    start = performance.now();
    for (let i = 0; i < iterations; i++) {
        Math.trunc(123.456);
    }
    end = performance.now();
    console.log(`Math.trunc: ${end - start}ms`);
    
    start = performance.now();
    for (let i = 0; i < iterations; i++) {
        123.456 | 0;
    }
    end = performance.now();
    console.log(`Bitwise OR: ${end - start}ms`);
}

Floating-Point Precision Issues

JavaScript uses the IEEE 754 double-precision floating-point format, which can lead to precision issues. For example:

console.log(0.1 + 0.2); // Output: 0.30000000000000004

When processing decimal parts, such precision errors may affect the final result. It is recommended to use integer arithmetic in scenarios requiring high precision or to employ specialized mathematical libraries.

Application Scenario Recommendations

Based on different usage scenarios, the following methods are recommended:

Conclusion

JavaScript offers multiple methods for removing the decimal parts of numbers, each with specific application scenarios and limitations. When choosing a method, developers should consider browser compatibility, performance requirements, number range limitations, and specific rounding rules. In modern development, Math.trunc() is the most recommended method, but bitwise operators are a better choice for extreme performance needs or when dealing with numbers within known ranges.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.