Home > Article > Web Front-end > How to Truncate Numbers to Two Decimals Without Rounding in JavaScript?
Preserving Precision: Truncating Numbers to Two Decimals Without Rounding
Often, when working with numbers, it becomes necessary to display them with a specific number of decimal places. However, using the built-in JavaScript function toFixed() may introduce unintended rounding. To address this, we must consider an alternative approach to accurately truncate numbers without rounding.
Solution: Conversion and Precision Control
To achieve this, we convert the number to a string and employ a regular expression to extract the desired number of decimal places.
function truncate(num, decimals) { return num.toString().match(RegExp(`^-?\d+(?:\.\d{0,${decimals}})?`))[0]; }
This function takes a number and the desired number of decimals as parameters. It returns a string representing the truncated value.
Example Usage:
const original = 15.7784514; const truncated = truncate(original, 2); console.log(truncated); // Output: "15.77"
In this example, the original value is truncated to two decimal places, resulting in "15.77."
Conclusion:
By harnessing string manipulation and regular expressions, we can effectively truncate numbers to a specified number of decimal places without introducing unwanted rounding. This technique ensures precision in displaying values, particularly when dealing with financial or scientific data.
The above is the detailed content of How to Truncate Numbers to Two Decimals Without Rounding in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!