I have a bunch of text box's on my page that involve numbers. The default value in the database is NULL when it is created and I have each input echo
the value it is in the database (by default nothing since it is set to null
).
The problem I am having is, if the user opens the form for the first time, submits the form and doesn't fill out an item, the value get's turned to 0
instead of keeping it null
.
Could anyone help me?
When a user opens the page, it formats the numbers like so:
if(isset($data['variable1']))
$variable1 = numberFormat($data['variable1']);
else
$variable1 = "";
When a user posts the form, it unformats the numbers like so:
$variable1 = numberUnformat($_POST['variable1']);
I have even tried doing this:
if(isset($_POST['variable1']))
$variable1 = numberUnformat($_POST['variable1']);
else
$variable1 = "";
numberFormat()
function numberFormat($n, $n_decimals="2")
{
return ((floor($n) == round($n, $n_decimals)) ? number_format($n) : number_format($n, $n_decimals));
}
numberUnformat()
function numberUnformat($number)
{
$cleanString = preg_replace('/[^0-9.,-]|(?<=.)-/', '', $number);
$onlyNumbersString = preg_replace('/[^0-9-]|(?<=.)-/', '', $number);
$separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1;
$stringWithCommaOrDot = preg_replace('/([,\.])/', '', $cleanString, $separatorsCountToBeErased);
$removedThousendSeparator = preg_replace('/(\.|,)(?=[0-9]{3,}$)/', '', $stringWithCommaOrDot);
return (float) str_replace(',', '.', $removedThousendSeparator);
}