我很困惑,因为如果我删除te .toFixed(2)然后条件将返回false,因此是正确的,但如果有.toFixed(2)它返回true,这是错误的.
此外,当我使用console.log显示包含值的两个变量时,它们都返回此值
5.00 and 20.00
Run Code Online (Sandbox Code Playgroud)
这是代码:
//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");
}
Run Code Online (Sandbox Code Playgroud)
我已经使用了没有.toFixed(2),因为那是正常工作但我希望能解释为什么会发生这种情况.
谢谢
T.J*_*der 12
因为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); // trueRun Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
96 次 |
| 最近记录: |