|
-
Oct 3rd, 2012, 06:08 PM
#1
Thread Starter
Addicted Member
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.
-
Oct 4th, 2012, 05:03 AM
#2
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
If my post was helpful to you, then express your gratitude using Rate this Post. 
And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet
Social Group: VBForums - Developers from India
Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...
-
Oct 4th, 2012, 06:50 PM
#3
Thread Starter
Addicted Member
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|