我有一個變量$amount,有時可以"0.00"。目前要檢查此變量是否具有值以及它是否不為零以下條件正在使用:if (!!$amount)何時$amount是"0.00"或"0,00"條件是true,而應該是false。最優雅的制作方法是什么false?我想過使用if ($amount === "0.0" || $amount === "0,00")和if (!!floatval($amount))但是沒有更好的方法嗎?更新:再次檢查,發現這.是一個小數分隔符,所以它不能是“0,00”。
1 回答

泛舟湖上清波郎朗
TA貢獻1818條經驗 獲得超3個贊
!!"0.0"并且!!"0,0"被評估為true因為它們被視為常規的非空字符串,因此不被視為假值。字符串中唯一被評估為 false 的零值是"0"
您可以使用正則表達式來檢查輸入是否僅包含字符0,.和,:
// returns false if $input contains a zero value
function CheckZeroes($input)
{
return !preg_match('/^[0.,]*$/', $input);
}
$inputs = [ 'a', '0.5', '0,5', '1,000', '1,000.42', '0', '0,0', '0.0', '' ];
foreach ($inputs as $input)
{
echo "'$input' returns " . (CheckZeroes($input) ? 'true' : 'false') . PHP_EOL;
}
這輸出:
'a' returns true
'0.5' returns true
'0,5' returns true
'1,000' returns true
'1,000.42' returns true
'0' returns false
'0,0' returns false
'0.0' returns false
'' returns false
- 1 回答
- 0 關注
- 244 瀏覽
添加回答
舉報
0/150
提交
取消