[英]why does 5.00 > 20.00 returns true for javascript parseFloat.tofixed(2)
我很困惑,因为如果我删除te .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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.