Number conver e.g 1.5k (k being thousand) to 1500
Hi,
Basically I am trying to large string numbers to a integer. Not really sure how to explain so I'll give a few examples:
So if I had an input number 1.5k (k being thousand) it would become 1500
or if I had
0.5m that would become 500000
This is the code I currently have which works:
PHP Code:
$numbers = array( '500000', '500k', '0.5m', '0.0005b' );
foreach( $numbers as $n )
{
$result = (in_array(substr ($n, -1), array('k', 'm', 'b')) ? substr ($n, -1) : null);
if($result !== null)
{
// Get the number.
$num = substr($n,0,-1);
if($result == 'k'){ // Thousand
$times = 1000;
}
elseif($result == 'm'){ // Million
$times = 1000000;
}
elseif($result == 'b'){
$times = 1000000000; // Billion
}
$n = $num * $times;
}
var_dump($n);
}
I'm just wondering if there is a better way to do this, maybe using regex? If possible I'd also like to remove all characters from the string that aren't K,M,B . or , to stop anything like 10k00k being input that would confuse the code.
Any help is appreciated, thank you.
Re: Number conver e.g 1.5k (k being thousand) to 1500
For regex, use the preg_match()
And a pattern like this might work:
Code:
/^[0-9][0-9\.,]*(k|b|m)?$/i
That is the first character should be a digit. Then followed by digits or dots or commas, for zero or more times. Then followed by "k" or "b" or "m" or nothing.
Am not good in regex. Maybe you'll get a better pattern than this. :)
Example:
PHP Code:
$num = "100,1230.0m";
$pattern = "/^[0-9][0-9\.,]*(k|b|m)?$/i";
if (preg_match($pattern, $num)) {
echo "Correct form";
} else {
echo "Incorrect form";
}
Hope it helps :wave:
Re: Number conver e.g 1.5k (k being thousand) to 1500
Thank you very much akhileshbc very helpful and I really appreciate it :)
I'm not too good at regex myself so its good to see how to do similar stuff in regex so I know for the future.