Strange behaviour of parseFloat of ‘this.innerHTML’ in Chrome

This is a rare case: in a project I use parseFloat JavaScript function to calculate final sum, but string was in the HTML code, previously generated by jQuery AJAX call:

$('#'+id).html(rezult+' '+currency);
...
$('#total').html('TOTAL:  '+totalcalc());

so it must be captured by innerHTML JS function. And parseFloat is used to clean the number, as it is shown on page like '123.45 USD'. Here is my totalcal() function:

function totalcalc() {
var tot = t;
$('.extra').each(function(){
var to = parseFloat(this.innerHTML.replace(',', '.'));
if(!isNaN(to)) tot += to;
});
return tot;
}

But in Google Chrome seems that innerHTML returns some hidden characters or codes (but I could not see them), and parseFloat retuns 'NaN'... Well, it is easy to extract numbers from a string (but spends me some time to understand that...). So here if the final code of the totalcalc() function, which works in all the "top 5" browsers:

function totalcalc() {
var tot = t;
$('.extra').each(function(){
var f = this.innerHTML.replace(',', '.').match(/([\d.]+)/);
if(f) tot += parseFloat(f[0]);
});
return tot;
}
This entry was posted in Blog, Hacks and tagged , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply