Mateo Guizado Mateo Guizado - 1 month ago 8
Javascript Question

compare two values ​in javascript works wrong

i try to compare some values of array and i need to get the minor value of object property but i have the next error.

this is my code:



//JavaScrit

var minValue = data.freight[0].localPrice;

console.log(minValue);

for (var i = 0; i < data.freight.length; i++) {

console.log('----------');
console.log(minValue);
console.log('>');
console.log(data.freight[i].localPrice);
console.log('----------');

if (minValue > data.freight[i].localPrice) {

minValue = data.freight[i].localPrice;

console.log('verdadero');

}else{

console.log('falso');

}
}





and this is the output:

Why 4.27 > 160.02 it´s true?

Why 4.27 > 160.02 it´s true? Help.

Answer

It is presumable that localPrice is a string. So you should use parseFloat() to get the float value and get expected results when comparing.

var minValue = parseFloat(data.freight[0].localPrice);

And in your if statement:

if (minValue > parseFloat(data.freight[i].localPrice)) {

    minValue = parseFloat(data.freight[i].localPrice);

    console.log('verdadero');

}
Comments