-3

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?

Josiah
  • 60
  • 6
artyak
  • 17
  • 6

2 Answers2

-1

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

or

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

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

Aldrin
  • 2,036
  • 15
  • 12
-1

A method that will fix your number to a set number of digits and then return it as a string is toFixed.

However, you should really be aware that you should never track currency using floats. The reason is that JavaScript (and a number of other languages) has issues with adding floats that can cause many unexpected data accuracy errors, and when you are talking about money you never want there to be any accuracy errors in how values are stored or presented. This has to do with some of the technicalities under-the-hood related to floating point precision.

For an easy demonstration of what I'm talking about, behold this somewhat perplexing example:

Boolean(0.2 + 0.1 === 0.3) // Returns false

Here is an article that will be helpful understanding this concept called "What Every JavaScript Developer Should Know About Floating Points"

The proper way to store currency is to convert to and from cent values using integer addition, so that in essence, 100 === $1.00. Then you use that in combination with the Intl.NumberFormat class to present the stored integers as currency.

More information on this way of storing and presenting currency can be found here.

Stephen M Irving
  • 1,324
  • 9
  • 20