hungrykoala hungrykoala - 1 month ago 10
Javascript Question

why does 5.00 > 20.00 returns true for javascript parseFloat.tofixed(2)

I am confused wit this since if I remove te .toFixed(2) then the condition will return false and thus be correct, but if there is .toFixed(2) it returns true which is wrong.

Also when I used console.log to display the two variables containing the values they both return this value

5.00 and 20.00


this is the code:

//this two values are actually populated from .val of an input field
var coupon_limit2 = 0;
var coupon_limit = $("#product_coupon_limit").val();
var sale_price = $("#product_product_list_price").val();


if(disc_type == "Percentage"){
if(coupon_type == "amount"){
coupon_limit2 = (coupon_limit/sale_price)*100;
}else{
coupon_limit2 = coupon_limit;
}
}else{
if(coupon_type == "percent"){
coupon_limit2 = (coupon_limit/100)*sale_price;
}else{
coupon_limit2 = coupon_limit;
}
}

var x = parseFloat($("#product_product_discount").val()).toFixed(2);
var y = coupon_limit2;

//returns correctly
if(x > parseFloat(y)){
alert("hi");
}

//returns wrong
if(x > parseFloat(y).toFixed(2)){
alert("hi");
}


I am already using the without .toFixed(2) since that's what's working properly but I just hope to have an explanation as to why this is happening.

Thank you

Answer

Because toFixed returns a string, and in a string comparison, anything starting with "5" is greater than anything starting with "2".

Gratuitous example:

var x = 5.0;
var y = 20.0;
console.log(typeof x);    // number
console.log(x > y);       // false
var xstr = x.toFixed(2);
var ystr = y.toFixed(2);
console.log(typeof xstr); // string
console.log(xstr > ystr); // true