Mario
Mario

Reputation: 885

php input with 1 decimal number

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

Answers (5)

Sunil Kartikey
Sunil Kartikey

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

Zheng Kai
Zheng Kai

Reputation: 3635

add a line:

$items['qty'] = sprintf('%.1f', $items['qty'])

Upvotes: 0

codaddict
codaddict

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']));

See it

Upvotes: 0

Nuno Costa
Nuno Costa

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

Yago Riveiro
Yago Riveiro

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

Related Questions