首页 > 解决方案 > How to correctly display 2 decimals in Javascript?

问题描述

There is a problem on my site. My price on things is displayed with two decimals after dot, for example 1.12, when i select a lot of positions, the total price becomes 14.619999999999997, this is all displayed through the JS. How can I limit so that 2 characters are displayed after the dot? To make it all readable, for example 15.77

My code:

function click() {
$('.de .item').click(function() {
    var i = parseFloat($(this).attr('data-id'));
    var price = parseFloat($(this).find('.price').find('b').text());
    if($(this).hasClass('active')) {
        delete(items[i]);
        $(this).removeClass('active');
        cost -= price;
    } else {
        items[i] = {
            classid : $(this).attr('data-classid'),
            assetid : $(this).attr('data-assetid')
        };
        $(this).addClass('active');
        cost += price;
    }

    $('#total_cost').text(cost);
    $('#skins_selected').text(getCount(items));
});
}

Responsible for the conclusion of the total price $('#total_cost').text(cost);

I try this method $('#total_cost').text(cost).toFixed(2); it doesn't want to work. And i try $('#total_cost') = parseFloat(text(cost)).toFixed(2); it doesn't work too.

How can I make the output correctly?

标签: javascriptjquery

解决方案


$('#total_cost').text(cost.toPrecision(2));

或者

function precise(num, precision = 2) {
    return Number.parseFloat(num).toPrecision(precision);
}

$('#total_cost').text(precise(cost));


推荐阅读