简体   繁体   中英

Comparing numbers - Unusual behaviour

Im getting 2 values from a table and I'd like to compare them. If one is grater than the other, then I alert some error. The thing is im getting a wrong result... for example I have 1000.00 and 1000000.00 and when I do 1000.00 > 1000000.00 Im getting a TRUE!, therefore an error, Why is that happening?

Hope someone can help me out here! Thx

row = document.getElementById(tabla).rows;
cell = document.getElementById(tabla).rows[0].cells;

for (i=2;i<row.length-1;i++){
    var TotalDist = parseFloat(document.getElementById(tabla).rows[i].cells[cell.length].firstChild.nodeValue).toFixed(2);
    var Total = document.getElementById(tabla).rows[i].cells[cell.length+1].firstChild.nodeValue;

    if(TotalDist>Total)
       alert("Error");
}

One of the values is already a float that I get from a db, the other one (TotalDist) is set by the user, so I convert it to float so that they can be compared properly... but it doesnt seem to be working

You need to convert both values to a number (ie use parseFloat on both strings) ->

row = document.getElementById(tabla).rows;
cell = document.getElementById(tabla).rows[0].cells;

for (i=2;i<row.length-1;i++){
    var TotalDist = parseFloat(document.getElementById(tabla).rows[i].cells[cell.length].firstChild.nodeValue).toFixed(2);
    var Total = parseFloat(document.getElementById(tabla).rows[i].cells[cell.length+1].firstChild.nodeValue);

    if(TotalDist>Total)
       alert("Error");

}

When using nodeValue a string is returned ... see the docs

var value = node.nodeValue;

value is a string containing the value of the current node

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM