Help - Search - Members - Calendar
Full Version: Price Validation In Php>
Zymic Webmaster Forums > Web Design & Development > Server Side Scripting > PHP
House
Right then.

Here's a function that will check if a number is valid for price.

It will also round up.

Example:

"Lisa enteres the price for a hotel room of £45.95 which VAT is then added too. This makes the number 57.99125

But oh noes! She can't take that from a bank account. She needs to round it...

*Enter House's house of rounding*"

Ok so enough of the shitty examples.

Code below.

CODE
<?php
// Price validation & rounding script.

// Input parameters = numeric value to validata & round up
// Output parameters = ErrorLeve (0 = pass, 1 = fail)
//                   & Rounded number

// Calling example - require("classes/class_main.php");
//                   $array_function = valid_number($number);
// Where $number = number to be validated & rounded.

function valid_number($number){
  if(is_numeric($number)){
    $number = number_format(round($number,2), "2", ".", ",");
    $errorlevel = 0;
  } else {
    echo "<b>Price validation & rounding script.</b><br>";
    echo "<br>";
    echo "Input parameters = numeric value to validata & round up<br>";
    echo "Output parameters = ErrorLeve (0 = pass, 1 = fail)<br>";
    echo "                  & Rounded number<br>";
    echo "<br>";
    echo "Calling example - require(\"classes/class_main.php\");<br>";
    echo "                  \$array_function = valid_number(\$number);<br>";
    echo "Where \$number = number to be validated & rounded.<br>";

    $errorlevel = 1;
  }
  return(array($errorlevel, $number));
} // End valid function
?>


Enjoy!
House
Good luck, have fun.
Ed
Because the "$array_function" variable isn't global, '$array_function does not exist within the scope of your script (only within the function), your $prot is your '$array_function' variable in the scope of the script, so print_r($prot).

CODE
$prot = valid_number($number, $errorlevel);


You could use http://www.php.net/money_format instead of 'number_format', I'd be inclined to do something like this for checking the price and returning it properly formatted:

CODE
function checkPrice($price)
{
   if(is_numeric($price))
      return sprintf('%01.2f', round($price, 2));
   else
      return false;
}


If you wanted a spot of regex to check the price, you could use:

CODE
preg_match('#^\d+(\.(\d+))?$#', $price)
House
lol as allways, thanks bread.

As you can see finished the script.

But as I say, cheers beers!
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2012 Invision Power Services, Inc.