[英]Matching float and string value in javascript not matched
I am using this code 我正在使用此代码
if(total == balance)
{
alert("test ok");
}
else
{
alert("test failed");
}
here total=10;
这里
total=10;
and balance=10.00;
balance=10.00;
but the result is "test failed". 但结果是“测试失败”。
Hmm... I may not be exactly correct, but I think total is taken as an integer and balance is taken as a decimal. 嗯...我可能并不完全正确,但是我认为总数被视为整数,余额被视为小数。 Try the
===
function instead of the ==
function. 尝试
===
函数而不是==
函数。
The ===
function converts the values and then checks them. ===
函数将转换值,然后检查它们。 So checking if a value is true
or false
depending on whether it is 0 or 1 requires the ===
operator to convert both into the same type of values. 因此,根据值是0还是1来检查值是
true
还是false
,需要===
运算符将它们都转换为相同类型的值。
And the ==
function just checks whether two values are equal, just by looking at the present value of it. ==
函数仅通过查看两个值是否相等就可以检查它们是否相等。 No conversion. 没有转换。 So if I want to check the values of two
int
values, I will use ==
. 因此,如果要检查两个
int
值的值,将使用==
。
There are two ways to solve this problem. 有两种方法可以解决此问题。
One is by changing either the total into a decimal, by giving it a value of 10.00 with a decimal or changing the balance into an int by giving it a value of 10, without the decimal places. 一种是通过将总数更改为小数,将其值设置为带小数的10.00,或将余额更改为整数,将其设置为值10,不带小数位。
The other is the better one, and you just have to replace your ==
with a ===
. 另一种是更好的方法,您只需将
==
替换为===
。 So your code would look like this: 因此,您的代码如下所示:
if (total === balance) {
window.alert("test ok");
} else {
window.alert("test failed");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.