Home > Web Front-end > JS Tutorial > How to Truncate Numbers to Two Decimal Places Without Rounding in JavaScript?

How to Truncate Numbers to Two Decimal Places Without Rounding in JavaScript?

Barbara Streisand
Release: 2024-11-10 05:44:02
Original
1016 people have browsed it

How to Truncate Numbers to Two Decimal Places Without Rounding in JavaScript?

Truncating Numbers to Two Decimal Places Without Rounding

When working with numbers in JavaScript, it's often necessary to display them with a certain number of decimal places. The toFixed() method can be used to round numbers to a specified number of decimal places, but what if you need to truncate the number without rounding?

Consider the following example:

var num = parseFloat(15.7784514);
document.write(num.toFixed(1) + "<br />");
document.write(num.toFixed(2) + "<br />");
document.write(num.toFixed(3) + "<br />");
document.write(num.toFixed(10));
Copy after login

This code results in the following output:

15.8
15.78
15.778
15.7784514000
Copy after login

As you can see, the toFixed() method rounds the number to the specified number of decimal places. To truncate the number instead, we can convert it into a string and use a regular expression to match the number up to the second decimal place:

function calc(theform) {
  var num = theform.original.value, rounded = theform.rounded
  var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]
  rounded.value = with2Decimals
}
Copy after login

This code converts the original number into a string, and then uses the regular expression ^-?d (?:.d{0,2})? to match the number up to the second decimal place. The resulting string is then assigned to the rounded element in the form.

This approach will truncate the number to two decimal places without rounding. For example, if the original number is 15.7784514, the truncated value will be 15.77.

The above is the detailed content of How to Truncate Numbers to Two Decimal Places Without Rounding in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template