How to convert this 19,500 string to number. If I do this
<?php
$val = "19,500";
$number = explode("," , $val);
$newnumber = $number[0].$number[1];
?>
But I don't think this is correct way.
You can replace the string ',' to '' and then convert into integer by int
<?php
$number = "19,500";
$updatedNumber = str_replace(',','',$number);
echo (int)$updatedNumber ;
NOTE: int is better to use than intval function.
It reduces overhead of calling the function in terms of Speed.
http://objectmix.com/php/493962-intval-vs-int.html
Try this:
<?php
$val = "19,500";
$val = str_replace(',', '.', $val);
$number = (float)$val;
?>
UPDATED: if comma comes out as a thousands-separator then:
<?php
$val = "19,500";
$val = str_replace(',', '', $val);
$number = (int)$val;
?>
, is used as a decimal point or a thousands-separator. In the US, your result would be off by a factor of a thousand -- even more if there were two commas.When I see your code it's just sting string(5) "19500"
<?php
$val = "19,500";
$number = explode("," , $val);
$newnumber = $number[0].$number[1];
var_dump($newnumber);
?>
so you can convert to integer like the following
<?php
$val = "19,500";
$number = explode("," , $val);
$newnumber = $number[0].$number[1];
$realinteger = (int)($newnumber);
var_dump($realinteger);
?>
So the result will be int(19500)
Just try this code
$val = "19,500";
$newnumber = intval(str_replace(',', '', str_replace('.', '', $val))); // output : 19500
$val = "19,500.25";
$newnumber = intval(str_replace(',', '', str_replace('.', '', $val))); // output : 1950025
you can edit delimiter that want to replace with balnk string :)
Or you can try this
$newnumber = preg_match("/[^0-9,. -]/", $val) ? 0 : preg_replace("/[^0-9.-]/", "",$val);
intval('19,500') would be equal to 19. But for integers, you want the decimal point (and everything after it) ignored, not interpreted as more digits. So, intval('19500.25') would be equal to 19500, which is almost certainly the desired result. Your example outputs a number a hundred times the string's numeric value.
,or you want to convert to integer?