-1

Possible Duplicate:
PHP regex - valid float number

what will be regular expression in php as well as for javascript for float numbers?

I waht to match values like 3, 3.3 or 0.3 and 0

0

5 Answers 5

3

There is no token for float numbers. If you want to match a float you have to use digit + point + digit, something like this:

\d+(\.\d+)?
Sign up to request clarification or add additional context in comments.

4 Comments

1.2.3.4.5 will match it. You've confused * quantifier with ?
@zerkms Oh right.. I'll edit, thanks!
\d+(\.\d+)? matches 3, 3.3, 0.3 & not 1.2.3.4.5
@KevinD. because I edited my answer
1

PHP:

is_numeric($nb);

JS:

!isNaN(+nb);

Comments

1

If you want to check if a given string is an int/float:

/^\d+(\.\d+){0,1}$/

If you want to match all numbers that in a given string:

/\b\d+(\.\d+){0,1}\b/g

That should give you what you need

Comments

0

It depends on what you want : Only check? do as Florian Margaine said : is_numeric($nb) in PHP for float numbers and ctype_digits($nb) for integers. in JS !isNaN(+nb); for float and typeof($nb) == "Integer" for integers.

If you want to convert your numbers (and check in the same time) :

//for floats
$floatNb = (float) $nb;
if($floatNb != 0 || $nb === "0")//now you are sure that $nb was a float and $floatNb is the float representation

If you got international numbers, use the number formatter from intl extension :

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$num = "1.234.567,891";
echo numfmt_parse($fmt, $num)."\n";

Regex are NEVER good for type checking

Comments

0

Float's can also be written as .3, this would be equal to 0.3 in that case to cover all you'd need:

/((?:\d)?(?:.\d+)?)/

This will group the result as one whole string, without splitting it into subresults.

So this would match 33, 3.3 & .33

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.