Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting int value from comma separated number php

Tags:

php

How do I turn a thousand-comma separated string representation of an integer into an integer value in PHP? (is there a general way to do it for other separators too?)

e.g. 1,000 -> 1000

Edit (Thanks @ghost) Ideally, decimals should be handled, but I could accept a solution that truncates at a decimal point.

like image 983
paullb Avatar asked Sep 22 '14 03:09

paullb


People also ask

How do you get each value from a comma separated string in PHP?

list($name,$job,$location) = explode(',',$employee); Note: this will obviously only work if the string is in the format you specified. If you have any extra commas, or too few, then you'll have problems. It's also worth pointing out that PHP has dedicated functions for handling CSV formatted data.

How can I get integer value in PHP?

PHP Casting Strings and Floats to Integers Sometimes you need to cast a numerical value into another data type. The (int), (integer), or intval() function are often used to convert a value to an integer.


1 Answers

If thats simple as it gets you could 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);
like image 195
Kevin Avatar answered Nov 16 '22 00:11

Kevin