How to remove decimals in JS
November 7, 2023
Understanding the need for removing decimals
Math object provides several methods to deal with decimals:
Math.floor() function rounds a number down to the nearest integer.
Math.ceil() rounds a number up to the nearest integer.
If you want to round to the nearest integer, use
To simply remove the decimal part without rounding,
Math.trunc() can be used.
Using bitwise operators
Bitwise operators can truncate decimals because they implicitly convert their operands to 32-bit integers.
The bitwise NOT operator
Applying the bitwise NOT operator twice will remove the decimal part of a number.
The left shift operator
Shifting zero places to the left also removes decimals.
parseInt function parses a string and returns an integer. It's commonly used to convert the string representation of a number to an integer, but it also works with actual number types by truncating decimals.
Number can also remove decimals, especially when dealing with floating-point issues.
Handling negative numbers
When dealing with negative numbers, be cautious with methods like
Math.ceil(), as they might not behave as expected:
Formatting as a string without decimals
To display a number without decimals without actually converting it to an integer, you can use the
toLocaleString method with options.
Handling large numbers and precision
For very large numbers or when dealing with precision, consider using libraries like
decimal.js which provide more control over numerical operations.
BigInt is a built-in object that provides a way to represent whole numbers larger than 2^53 - 1.
Using a library
A library like
decimal.js can handle arbitrary precision and complex calculations:
How to Truncate Date in MySQL