Domanda

I have problem with calcualting float values via javascript.

first my code

var d_val = 0.00;
$.each($('.prices a b'), function(index,obj){
    d_val = parseFloat( $(obj).text().replace( '€', '' ) );
    group_price +=   d_val;
});
console.log( '-----> '+ group_price );

when i run this code when adding new elements into ".prices" firebug prints...

-----> 0.8
-----> 1.6
-----> 2.4000000000000004
-----> 3.2

$('.prices a b') has alltime a string like 0.80€ or 0.50€ Does somebody has an idea, what the problem is?

È stato utile?

Soluzione

Try this:

 var mycurrency = ['0.80€', '0.60€', '0.50€', '0.506€'], sum = 0;
 $.each(mycurrency, function(i, obj){
 var myval = parseFloat(obj.replace('€', '')).toFixed(2);
 console.log('--->', myval);
 sum += parseFloat(myval);
 });
 console.log('--->', sum, '(Sum)');

---> 0.80

---> 0.60

---> 0.50

---> 0.51

---> 2.41 (Sum)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top