简体   繁体   English

PHP零浮点返回true

[英]PHP zero float returning true

I have a field in my mySQL db table of type decimal (15,4) 我在mySQL db表中有一个十进制类型的字段(15,4)

I've never experienced this before but if the value is 0.0000 my PHP if statement is returning true! 我以前从未体验过这个,但如果值为0.0000我的PHP如果语句返回true!

As a sanity check I even did: 作为一个完整性检查我甚至做了:

if(0.0000) echo "Hello World";

And sure enough, Hello World echo'd out. 可以肯定的是,Hello World回应了。 What the hell is going on? 这到底是怎么回事? Anybody got any ideas? 有人有任何想法吗?

If it's a float value coming out from DB it will be treated like a string, not like a numeric value. 如果它是从DB发出的浮点值,它将被视为字符串,而不是数字值。 You can try something this: 你可以试试这个:

if(floatval($value) > 0) { ... }

Where $value contains the value from DB. 其中$value包含DB的值。

I think the problem is you got a string "0.0000" from db but not 0.0000 . 我认为问题是你从db得到一个字符串"0.0000"而不是0.0000

Try again with: 再试一次:

if ((int)$your_value) echo "Hello World";

I don't have this behavior on my PHP version (5.3.3). 我的PHP版本(5.3.3)上没有这种行为。

I suggest casting the number to bool before doing the check: if ((bool) $float) . 我建议在进行检查之前将数字转换为boolif ((bool) $float)

I know it's been a long time since this question was opened but I thought it might help out someone else. 我知道自从这个问题被打开以来已经有很长一段时间了,但我认为这可能有助于其他人。

A float is actual an approximation of the Real Number . 浮点实际上是Real Number的近似值。 You will find that not all Real numbers can be represented by a float. 您会发现并非所有Real numbers都可以用浮点数表示。 This might be the reason why you are getting unexpected results. 这可能是您获得意外结果的原因。 You should have a read of http://php.net/manual/en/language.types.float.php . 你应该阅读http://php.net/manual/en/language.types.float.php

If however you need higher precision you should look at using the BC Math lib's http://php.net/manual/en/ref.bc.php . 但是,如果您需要更高的精度,则应该使用BC Math lib的http://php.net/manual/en/ref.bc.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM