为什么5.00 >20.00对javascript parseFloat.tofixed(2)返回true

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

本文关键字:tofixed 返回 true parseFloat 为什么 javascript      更新时间:2023-09-26

我对此感到困惑,因为如果我删除。tofixed(2),那么条件将返回false,因此是正确的,但如果有。tofixed(2),它返回true,这是错误的。

当我使用console.log显示包含值的两个变量时它们都返回这个值

5.00 and 20.00

这是代码:

//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"); 
}

我已经使用没有。tofixed(2),因为这是什么工作正常,但我只是希望有一个解释,为什么会发生这种情况。

谢谢

因为toFixed返回一个字符串,并且在字符串比较中,任何以"5"开头的都大于以"2"开头的。

无端的例子:

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