how to extract a number with decimal (dot and comma) from a string (e.g. 1,120.01) ? I have a regex but doesn't seem to play well with commas
preg_match('/([0-9]+\.[0-9]+)/', $s, $matches);
how to extract a number with decimal (dot and comma) from a string (e.g. 1,120.01) ? I have a regex but doesn't seem to play well with commas
preg_match('/([0-9]+\.[0-9]+)/', $s, $matches);
The locale-aware float (%f) might be used with sscanf.
That doesn't split the parts into an array though. It simply parses a float.
See also: http://php.net/manual/en/function.sprintf.php
A regex approach:
The correct regex for matching numbers with commas and decimals is as follows (The first two will validate that the number is correctly formatted):
decimal optional (two decimal places)
Debuggex Demo
Explained:
Will Match:
Will not Match
decimal mandatory (two decimal places)
Debuggex Demo
Explained:
Will Match:
Will Not Match:
Matches Numbers separated by commas or decimals indiscriminately:
Debuggex Demo
Explained:
Will Match:
Will Not Match:
Note: wrap either in a group and then just pull the group, let me know if you need more specifics.
Description: This type of RegEx works with any language really (PHP, Python, C, C++, C#, JavaScript, jQuery, etc). These Regular Expressions are good for currency mainly.
You can use this regex: -
Explanation: -
Add the comma to the range that can be in front of the dot:
And this regex:
Will only match
But not
Here is a great working regex. This accepts numbers with commas and decimals.
This should work