Home > Web Front-end > JS Tutorial > body text

Why is toFixed(2) Rounding Incorrectly for Certain Decimal Values?

Patricia Arquette
Release: 2024-10-22 14:40:02
Original
417 people have browsed it

Why is toFixed(2) Rounding Incorrectly for Certain Decimal Values?

Javascript toFixed Rounding Discrepancies

toFixed(2) is not rounding up for certain decimal values, displaying 859.38 instead of 859.39 in the example provided. This discrepancy can be attributed to variations in browser implementations of the toFixed() method.

To circumvent this issue and ensure consistent rounding across browsers, consider utilizing the toFixed10() method recommended by blg. This method provides accurate rounding even for extended precision values.

Here's an updated code snippet that incorporates toFixed10():

function toFixed(num, precision) {
    return (+(Math.round(+(num + 'e' + precision)) + 'e' + -precision)).toFixed(precision);
}
...
$('#lblTotalSprice').text('$' + addCommas(toFixed(currSprice, 2)));
$('#lblTotalPrice').text('$' + addCommas(toFixed(currPrice, 2)));
$('#lblTotalDiscount').text('$' + addCommas(toFixed(currDiscount, 2)));
$('#lblTotalDeposit').text('$' + addCommas(toFixed(currDeposit, 2)));
Copy after login

The above is the detailed content of Why is toFixed(2) Rounding Incorrectly for Certain Decimal Values?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!