Reputation: 885
all, I'm making a shopping cart that only accept input number with 1 decimal place. The following is piece of code I get from a library (with some modification):
$items['qty'] = trim(preg_replace('/([^0-9\.])/i', '', $items['qty']));
This will accept any number. but I want to make it as only 1 decimal. how to modify the code?
Thanks
Upvotes: 0
Views: 381
Reputation: 525
this can be done with round function
echo round(153.751, 1); // 153.8
this will help Rounding numbers with PHP
Upvotes: 1
Reputation: 455312
You can remove the decimal places after the first decimal place:
$items['qty'] = trim(preg_replace('/[^0-9\.]+|(?<=\.[0-9])[0-9+]+/', '', $items['qty']));
Upvotes: 0
Reputation: 423
If i understand well the question, you can use number_format
$items['qty'] = number_format(trim(preg_replace('/([^0-9\.])/i', '', $items['qty'])),1,".","");
Hope it helps.
Upvotes: 0
Reputation: 727
You can use a regex like ^(\d+.{0,1}\d*)$
But PHP have a concept, the filter, that does a lot of validations for you, http://php.net/manual/en/filter.filters.validate.php
Upvotes: 0