Unexpected parseFloat behavior with this.innerHTML in Chrome

This was an unusual case. In one project, I used the JavaScript parseFloat() function to calculate a final total, but the value came from HTML previously generated by a jQuery AJAX request:

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

The value therefore had to be read through innerHTML. I used parseFloat() to extract the numeric part from a displayed value such as 123.45 USD. Here is the original totalcalc() function:

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

In Google Chrome, however, innerHTML appeared to return hidden characters that I could not see, and parseFloat() returned NaN. The solution was to extract the numeric characters explicitly. The final totalcalc() function worked in the five major browsers at the time:

function totalcalc() {
var tot = t;
$('.extra').each(function(){
var f = this.innerHTML.replace(',', '.').match(/([\d.]+)/);
if(f) tot += parseFloat(f[0]);
});
return tot;
}

Share this

This entry was posted in Blog, Hacks and tagged , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply