In PHP, is there an easy way to convert a number to a word? For instance, 27 to twenty-seven.
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
Here's a small class I wrote tonight. Caveats:
longform
method doesn't handle decimals. It just erases them. Feel free to modify this and add that functionality if you wish.numberformat
method does do decimals, but doesn't do any rounding. I had to create a newnumberformat
function because of PHP's inherent limitations with integer sizes. I was translating numbers so big that when I usednumber_format()
to check my translations, it took me 30 minutes to realize my translations weren't wrong,number_format
was.2,147,483,647
(2 billion and change). 64-bit versions will handle up to like9 quintillion
or something. BUT that's irrelevant here as long as you feed the numbers to thelongform
method as astring
. I did a 306-digit number overajax
from a webform just fine, as long as I passed it to the server as''+number
.So, this class will translate numbers up to
999 Centillion, 999 etc.
(e.g., a string of 9s 306 characters long). Any number bigger than that and the function just returns a dumb message.Usage:
The optional second boolean parameter defaults to true, which adds commas as best it can in the right places, to make the number more readable.
By the way, you can put a
-
at the front if you want it to be negative, but any other characters included in the inputted string will be stripped out. For instance:reallyBig::longform('-C55LL-M5-4-a-9u7-71m3-M8');
will output:negative five billion, five hundred fifty-four million, nine hundred seventy-seven thousand, one hundred thirty-eight
The
numberformat
method isn't necessary for any other method. It's just there if you want to check a really long translated number. Since all these functions handle numbers as strings, they don't run up against PHP's limitations.The only reason I stopped at a 999 centillion is because centillion was the last number on the website I was looking at when I couldn't remember what came after a decillion.