data type conversion - PHP function to safely return a float from string -
let's have form ask product's price. basically, don't consider case user adds thousands comma, is: 1,000.00 or 1,000,000.00
i consider case user inputs 1000.00 or 1000,00 or 1000000.00 never 1,000.00, or 10,000,000.00 or, worst, 10.000.000,00
i came function.
function getprice($price) { if (is_string($price)) { if (strpos($price, ",") !== false) { $price = str_replace(',', '.', $price); } } return (is_numeric($price)) ? floatval($price) : false; } do consider safe function? can point improovements?
you function looks ok me except last line floatval.
my main consideration approach php not represent float correctly to: floatval, casting float or arithmetic operations float variables.
for example php may convert 10000.00 9999,99 depending on precision set. (you can read more here http://php.net/manual/en/language.types.float.php)
if need prices arithmetic calculations after parsing them float (in getprice function) , need precision advice avoid parsing float , either:
- leave them string , calculations strings
- use
bc mathextension more precise math operations in php
Comments
Post a Comment