Reputation: 3854
I have a number that is a string with a value of "53 MILLION".
$number="53 MILLION";
I want this number to be 53,000,000. How would go about doing this? I tried using the number_format function but with no luck.
Thanks in advance!
$number="53 MILLION";
$number= str_replace($number, "MILLION", "000,000");
echo $number; //000,000 instead of 53,000,000
Upvotes: 1
Views: 429
Reputation: 22847
Depends how example is your question
Your real case could be:
convert 53 MILLION 39 TOUSEND 334
into 53,039,334
etc.
So the algorithm would be to tokenize a string, wherever a number is available, remember it on stack. Wherever one of THOUSEND, MILLION, etc.
is available, multiply what you have on stack and add to number. At the end add what is left without multiplying. Then you have the number.
Convert the number into number-string (53039334) and, going from end, after each 3 digits add coma, and here you have what you need :)
Upvotes: 0
Reputation: 14479
Building on what Jesus said, a simple function to construct these numbers would be:
function declare_number($number_string){
$find_replace = array(
' HUNDRED' => '00',
' THOUSAND' => ',000',
' MILLION' => ',000,000',
' BILLION' => ',000,000,000'
);
return str_ireplace(array_keys($find_replace),$find_replace,$number_string);
}
This would also be able to convert 8 hundred thousand = 800,000 etc.
Upvotes: 2
Reputation: 785128
If you just have million number then use:
$number = str_replace(' million', '000000', $number);
Upvotes: 1
Reputation: 519
Dont know PHP but have an algorithm
Algorithm for "53 Million, 2 hundred-thousand, 8 hundred":
Size String Translation Table = [{"Million", 1000000},{"Thousand", 1000}, etc...]
counter = 0
--Scan from top of string to end:
----until comma
------scan integer - "53"
------scan size string - "Million"
------multiply integer by size string translation - "53 * 1000000"
------Add to the main counter - counter += "53000000"
----loop
--end
Upvotes: 0
Reputation: 839
Why not just split your string, search for the "MILLION" substring within your array, then exchange it for "000,000", then put it all back together? I suppose you can use spaces for the split.
Upvotes: 1