I am currently validating US Currency along with a decimal number format. I am using the function money_formatbut the issues is that certain values is returning an error.
How can i have the function work when the input value is 0.00 or 0.50? Example
PHP
if (isset($_POST['price'])){
$price = $_POST['price'];
$priceString = empty($price['price'])?null:trim($price['price']);
if(!empty($priceString)) {
$price = str_replace("$", "", $price);
if (preg_match('/^[+\-]?\d+(\.\d+)?$/', $price)){
echo ('<div id="price"><span id="resultval"><h2>Price:</h2>'.money_format('%n', $price).'</span></div>');
}
else {
echo ('<div id="price"><span id="resultval"><h2>Price:</h2><div class="errorMessage">Enter a valid number in US currency format.</div></span></div>');
}
}
else {
echo '';
}
}
The error is here:
Note that that
$priceis a String; so,$price['price']returns the first character of that array because the interpreter should logically attempt$price[intval('price')]whereintval('price') == 0. Consequently,$price['price'] == $price[0].For example, if the input was
0.00, then$price['price']would return0which is considered empty according to the PHP manual.I think you intend for the following (which works with
0.00and0.50):