Qualcuno sa come convertire un numero come 1, 2 o 3 nella loro versione di testo (uno, due, tre) in PHP? Ho solo bisogno di convertire da 1 a 99. So che potrei scrivere un'enorme dichiarazione di commutazione, ma sarebbe ridicolo.Conversione di un numero (1, 2, 3) in una stringa (uno, due, tre) in PHP
risposta
pera ha un pacchetto Numbers_Words:
$numberToWord = new Numbers_Words(); echo $numberToWords->toWords(200);
+1 Non sapevo che esistesse. –
+1 Sembra proprio a me. –
Oppure: 'Numbers_Words :: toWords (200)' –
Non proprio l'ideale, ma atleast meglio di un 'istruzione switch enorme':
$numbermappings = array("zero", "one","two","three", "four" .... "ninetynine");
echo $numbermappings[4]; // four
Hai ancora a scrivere che vasta gamma anche se ..
Utile se non hai bisogno di una grande quantità di numeri. – trueinViso
Vedi this function in action:
function N2L($number)
{
$result = array();
$tens = floor($number/10);
$units = $number % 10;
$words = array
(
'units' => array('', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eightteen', 'Nineteen'),
'tens' => array('', '', 'Twenty', 'Thirty', 'Fourty', 'Fifty', 'Sixty', 'Seventy', 'Eigthy', 'Ninety')
);
if ($tens < 2)
{
$result[] = $words['units'][$tens * 10 + $units];
}
else
{
$result[] = $words['tens'][$tens];
if ($units > 0)
{
$result[count($result) - 1] .= '-' . $words['units'][$units];
}
}
if (empty($result[0]))
{
$result[0] = 'Zero';
}
return trim(implode(' ', $result));
}
C'è un pacchetto PEAR che fa questo. Lo fa il numero MODO superiore al 99 ed è multi-lingua, quindi potrebbe essere più pesante del necessario, ma ancora la pena di verificare:
Ecco quello che ho scritto nel lontano college. Include anche il supporto per i numeri negativi. So che ci sono alcuni modi in cui potrebbe essere abbreviato e/o ripulito, ma hey, funziona bene per qualsiasi numero intero!
/**
Converts an integer to its textual representation.
@param num the number to convert to a textual representation
@param depth the number of times this has been recursed
*/
function readNumber($num, $depth=0)
{
$num = (int)$num;
$retval ="";
if ($num < 0) // if it's any other negative, just flip it and call again
return "negative " + readNumber(-$num, 0);
if ($num > 99) // 100 and above
{
if ($num > 999) // 1000 and higher
$retval .= readNumber($num/1000, $depth+3);
$num %= 1000; // now we just need the last three digits
if ($num > 99) // as long as the first digit is not zero
$retval .= readNumber($num/100, 2)." hundred\n";
$retval .=readNumber($num%100, 1); // our last two digits
}
else // from 0 to 99
{
$mod = floor($num/10);
if ($mod == 0) // ones place
{
if ($num == 1) $retval.="one";
else if ($num == 2) $retval.="two";
else if ($num == 3) $retval.="three";
else if ($num == 4) $retval.="four";
else if ($num == 5) $retval.="five";
else if ($num == 6) $retval.="six";
else if ($num == 7) $retval.="seven";
else if ($num == 8) $retval.="eight";
else if ($num == 9) $retval.="nine";
}
else if ($mod == 1) // if there's a one in the ten's place
{
if ($num == 10) $retval.="ten";
else if ($num == 11) $retval.="eleven";
else if ($num == 12) $retval.="twelve";
else if ($num == 13) $retval.="thirteen";
else if ($num == 14) $retval.="fourteen";
else if ($num == 15) $retval.="fifteen";
else if ($num == 16) $retval.="sixteen";
else if ($num == 17) $retval.="seventeen";
else if ($num == 18) $retval.="eighteen";
else if ($num == 19) $retval.="nineteen";
}
else // if there's a different number in the ten's place
{
if ($mod == 2) $retval.="twenty ";
else if ($mod == 3) $retval.="thirty ";
else if ($mod == 4) $retval.="forty ";
else if ($mod == 5) $retval.="fifty ";
else if ($mod == 6) $retval.="sixty ";
else if ($mod == 7) $retval.="seventy ";
else if ($mod == 8) $retval.="eighty ";
else if ($mod == 9) $retval.="ninety ";
if (($num % 10) != 0)
{
$retval = rtrim($retval); //get rid of space at end
$retval .= "-";
}
$retval.=readNumber($num % 10, 0);
}
}
if ($num != 0)
{
if ($depth == 3)
$retval.=" thousand\n";
else if ($depth == 6)
$retval.=" million\n";
if ($depth == 9)
$retval.=" billion\n";
}
return $retval;
}
Perché la nuova riga dopo cento, mille, milioni e miliardi? Non dovrebbe essere uno spazio? – bdsl
Questo è sbagliato per un trilione e numeri più grandi. – bdsl
Ha scritto per qualsiasi ** intero **. Poiché il valore massimo di un intero è 2147483647 per un sistema a 32 bit in php, è fondamentalmente corretto con la sua affermazione! Inoltre a 64 bit per php è iniziato nel 2008 sperimentalmente, quindi è lealmente che intendeva il valore massimo per 32-bit. – geisterfurz007
Ho finito per dover scrivere questo per un test di codifica durante un processo di intervista. Si può vedere il mio codice finale a Github qui: https://github.com/mangs/integers2words
Per comodità, qui è la classe DemoLibrary che implementa questa funzionalità int2str() (tutti i membri della classe sono lì solo per supportare la funzionalità int2str()
):
<?php
/**
* Demo library class intended to be added to in the future
*/
class DemoLibrary {
/***** NOTE: a const cannot be an array in PHP, so making these arrays static is the next best thing *****/
/**
* @var array $_numbersUnder20 Array containing the word associated with the index's number value
*/
private static $_numbersUnder20 = [
'zero', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
];
/**
* @var array $_tensDigits Array containing all tens digit values except 10
*/
private static $_tensDigits = [
'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'
];
/**
* @var array $_orderOfMagnitude Array containing the higher-order digit values; can also be
* thought of as the order of magnitude of the target digit
*/
private static $_orderOfMagnitude = [
// Stopped at "quintillion" because the maximum PHP int value on 64-bit Linux is
// 9,223,372,036,854,775,807 (a.k.a. 2^63 - 1 because PHP doesn't support unsigned ints)
'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion'
];
/**
* Recursively calculates the string-, word-based equivalent of the target integer
*
* @param integer $num Integer whose value will be converted to a word-based string
* @param boolean $recursive Determines if the currently-executing code is being called
* recursively; allows for non-recursive 0 to be converted to "zero"
* otherwise use an empty string
*
* @throws InvalidArgumentException if the first argument is not of type int
*
* @return string Partially- or fully-built word-based representation of the target integer
*/
private function _integerToWords($num, $recursive=false) {
// Ensure a valid integer
if(!is_int($num)) {
throw new InvalidArgumentException(
__FUNCTION__ . ' expects parameter 1 to be of type integer; actual type: ' .
gettype($num)
);
}
/***** Perform the int to string conversion based on the size of $num *****/
// Negative
if($num < 0) {
return 'negative ' . $this->_integerToWords(-1 * $num, true);
}
// 0 or no value in the lowest digits
if($num === 0) {
return $recursive ? '' : 'zero';
}
// 1-19
if($num < 20) {
return self::$_numbersUnder20[$num];
}
// 20 - 99
if($num < 100) {
$highDigitValue = intval(floor($num/10) - 2); // Value of the highest-order digit
$remainingValue = $num % 10; // Value of the remaining digits
return
self::$_tensDigits[$highDigitValue] .
'-' .
$this->_integerToWords($remainingValue, true);
}
// 100 - 999
if($num < 1000) {
$highDigitValue = intval(floor($num/100)); // Value of the highest-order digit
$remainingValue = $num % 100; // Value of the remaining digits
return
$this->_integerToWords($highDigitValue, true) .
'-hundred ' .
$this->_integerToWords($remainingValue, true);
}
// 1,000+
$quotient = $num;
$divideCount = 0;
while($quotient >= 1000) {
$quotient /= 1000;
++$divideCount;
}
$highDigitValue = intval(floor($quotient)); // Value of the highest-order digit
$remainingValue = $num - ($highDigitValue * pow(1000, $divideCount)); // Value of the remaining digits
return
$this->_integerToWords($highDigitValue, true) .
'-' .
self::$_orderOfMagnitude[$divideCount - 1] .
' ' .
$this->_integerToWords($remainingValue, true);
}
/**
* @api
*
* Calculates the string-, word-based equivalent of the target integer
*
* @param integer $num Integer whose value will be converted to a word-based string
*
* @return string Fully-built word-based representation of the target integer
*/
public function int2str($num) {
return trim($this->_integerToWords($num), "- \t\n\r\0\x0B");
}
}
- 1. Transform [: uno, 1,: due, 2] a {: uno => 1,: due => 2} in Ruby
- 2. .NET converti numero in rappresentazione stringa (1 a 1, 2 a 2, ecc ...)
- 3. TypeScript Conversione di una stringa in un numero
- 4. Conversione di una stringa in un costante definita in PHP
- 5. Conversione di un intero in una stringa in PHP
- 6. Come trasformare un numero (1,2,3, ecc.) In un numero ordinale (1 °, 2 °, 3 ° ecc.) Usando xslt
- 7. conversione del numero in stringa in lisp
- 8. Conversione di una stringa in numero intero in Schema
- 9. Conversione di un array Bash in una stringa delimitata
- 10. Estrazione di un numero da una stringa di 1 parola
- 11. Conversione di una stringa in BigInteger
- 12. Conversione di un FFT in uno spettogramma
- 13. scambia due parole in una stringa php
- 14. Conversione di un byte in una stringa binaria in C#
- 15. Aggiungere 2 valori a 1 chiave in un array PHP
- 16. Conversione di una stringa in un doppio
- 17. Verifica se una stringa termina con un numero in PHP
- 18. Conversione di una stringa in un elenco in Python
- 19. Verificare se una stringa inizia con un numero in PHP
- 20. Trasferimento di un numero in una stringa in TypeScript
- 21. Conversione di un elenco generico in una stringa CSV
- 22. Conversione di una stringa in una data in una cella
- 23. Conversione di due elenchi in una matrice
- 24. Conversione stringa javascript in array php
- 25. Conversione di una stringa HTML in un elemento DOM?
- 26. Conversione di un numero decimale in un numero misto (base)
- 27. Conversione da stringa a numero intero
- 28. Qual è la prova di (N-1) + (N-2) + (N-3) + ... + 1 = N * (N-1)/2
- 29. conversione di una stringa in dizionario Python
- 30. Conversione di un dizionario in una lista
possibile duplicato di [C'è un modo semplice per convertire un numero in una parola in PHP?] (http://stackoverflow.com/questions/277569/is-there-an-easy-way-to-convert-a-number -to-a-word-in-php) –
risposta soddisfatta qui [http://stackoverflow.com/questions/14314997/how-to-convert-amount-in-number-to-words](http://stackoverflow .com/questions/14314997/how-to-convert-importo-in-numero-a-parole) –