开发者

Jquery - Sum bug with various price formats

I have problems to calculate price with jquery in various price formats (depending on the language).

With German: 1.375,50 € (Returns 1.38 €)
English format: €1,375.50 (don't work)
French format: 1 375,50 € (Returns 1.00 €)
Italian format: €1,375.50 (don't work)
Spanish format: € 1.375,50 (don't work)

Here is a link of my working demo : http://jsfiddle.net/QmTNZ/63/

And here is my code :

function ca(){
    var $overall = 0;

    $("tr.sum").each(function() {

        var $qnt = $(this).find(".qty");
        var $price = $(this)开发者_如何学JAVA.find("td").eq(2);

        console.log($qnt + " | " + $price);

        var sum = parseFloat($price.text().replace(",", ".")) * parseFloat($qnt.val().replace(",", "."));

        if(isNaN(sum)) {
            sum = 0;
        }
        $(this).find("td").eq(3).text(Math.round(sum * 100) / 100);

        $overall += sum;

    });

    $("#total").text($overall);
}

$(function() {

    ca();
    $('input.qty').bind('change keyup',function(){ca();});

});

The price "td" can contain other texts, for example "Incl. 19% tax".

My questions here is how can I use a css class that englobe only the price, without the Euro Symbol, to use it in calculation, and how can I avoid the problems of the dot and comma in price calculation in all price formats.

(I'm always beginner in jquery....)

Thanks for help !


Regardless of anything else, your code is going to have to know the formatting rules for the locale, otherwise you won't be able to correctly format your resulting sum.

However, you can avoid worrying about the locale differences in the main body of your code by separating out the price data from the price display. One way you can do that is with a data-* attribute on the element containing the price display.

For instance, let's suppose your row looks like this currently:

<tr><td>Widget</td><td>1</td><td>1 375,50 €</td></tr>

There, the 3rd cell contains the price as text with the various formats. Now, when outputting the table, if you include the price as a data-price attribute in a known, specific format, you avoid all this hassle:

<tr><td>Widget</td><td>1</td><td data-price="1375.5">1 375,50 €</td></tr>

You can then access it via attr("data-price"):

var thisPrice = parseFloat($(this).find("td:eq(2)").attr("data-price"));

This gets you the prices in a nice reliable way.

But again, in the end, you'll need to know the locale rules in order to display $overall in the correct format.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜