Getting int value from php comma number

How to turn a comma-separated string representation of an integer into an integer value in PHP? (is there a general way to do this for other delimiters?)

eg 1,000 -> 1000 

Edit (thanks @ghost) Ideally, decimal fractions should be handled, but I could make a decision that truncates at the decimal point.

+8
source share
3 answers

If it's simple, as you can use filter_var() :

 $number = '1,000'; $number = (int) filter_var($number, FILTER_SANITIZE_NUMBER_INT); var_dump($number); 

or

 $number = '1,000.5669'; $number = (float) str_replace(',', '', $number); var_dump($number); 
+11
source

You can mark a specific character with str_replace and distinguish it as an integer with intval . A regular expression filter can also be used to determine if the input string is formatted correctly. Here is what this code looks like:

 <?php function remove_delimiters_simple($string, $delimiter = ',') { // Removes all instances of the specified delimiter and cast as an integer // Comma (,) is the default delimiter return (int) str_replace($delimiter, '', $string); } function remove_delimiters_advanced($string, $delimiter = ',') { // Use preg_quote in case our delimiter is '/' for some reason // The regular expression should match validly formatted numbers using a delimiter // every 3 characters $valid_format_expression = sprintf( '/^\d{1,3}(%s\d{3})*$/', preg_quote($delimiter, '/') ); // If not a validly formatted number, return null if (! preg_match($valid_format_expression, $string)) { return null; } // Otherwise, return the simple value return remove_delimiters_simple($string, $delimiter); } 
+3
source

If you use PHP> = 5.3, you can use numfmt_create () , for example:

 $fmt = numfmt_create( 'nl_NL', NumberFormatter::TYPE_INT32 ); $num = "1,000"; echo numfmt_parse($fmt, $num); //gives 1000 

Note :: nl_NL is the language you used in the format number, and it should be the same when used for numfmt_create

+1
source

Source: https://habr.com/ru/post/975620/


All Articles