Actualmente tenemos un mecanismo rudimentario para convertir números en palabras (por ejemplo, usando algunas matrices estáticas) y, según el tamaño del número, lo traducimos a un texto en inglés. Pero nos encontramos con problemas de números que son enormes.
10183 = Ten thousand one hundred eighty three
90 = Ninety
5888 = Five thousand eight hundred eighty eight
¿Hay una función fácil de usar en alguna de las bibliotecas matemáticas que pueda usar para este propósito?
Esto podría ser útil stackoverflow.com/questions/3911966/…
– Bu Said
12 de noviembre de 2020 a las 21:41
ICU4J contiene un buen soporte para deletrear números. Los archivos con las “reglas” se pueden editar fácilmente, y no hay problema para agregar otros idiomas (lo hicimos, por ejemplo, para polaco y ruso).
No, pero hicimos esto hace algunos años, y si no recuerdo mal, necesitábamos algunas cosas adicionales. ¡Pero es bueno saberlo!
– Landei
12 de octubre de 2010 a las 17:18
RBNF ha tenido revisiones importantes hace aproximadamente un año, tanto en CLDR como en ICU. Echale un vistazo.
–Steven R. Loomis
12 de octubre de 2010 a las 17:36
Esta debe ser la respuesta seleccionada ya que las otras dependen de implementaciones de ejemplo no localizadas y con errores
– ooxi
30 de junio de 2014 a las 4:46
¡Sí! Esta debería ser una respuesta seleccionada… Funcionó de maravilla… Se traduce a cualquier idioma, cualquier región, cualquier país como se indica aquí iana.org/assignments/language-subtag-registry/….. El uso es tan simple como. RuleBasedNumberFormat ruleBasedNumberFormat = new RuleBasedNumberFormat( new Locale("EN", "US"), RuleBasedNumberFormat.SPELLOUT ); System.out.println(ruleBasedNumberFormat.format(value));
– Muthu Ganapatía Nathan
18 de abril de 2015 a las 10:47
solo necesito esto solo para ingles
– Jasón
12 de octubre de 2010 a las 6:03
@Jason, estaba respondiendo a la pregunta “¿Hay una función fácil de usar en alguna de las bibliotecas matemáticas que pueda usar para este propósito?”
– Yanick Rochón
12 de octubre de 2010 a las 6:09
¿Inglés americano o inglés británico? Billón tiene diferentes significados entre estas culturas.
– Don Roby
24 de julio de 2011 a las 23:11
@Don Roby – AFAIK, esa es solo una preocupación histórica. La mayoría de los británicos usan el significado del inglés americano en estos días. (Por supuesto, hay algunos excéntricos que escriben cartas (en tinta verde) a The Times sobre este tipo de cosas, pero probablemente no se darán cuenta, debido a que se niegan a aprender a usar computadoras :-))
– Esteban C.
25 de julio de 2011 a las 1:09
@Rochon: ¡Buen código! Me ayudó mucho … pero tiene un pequeño error … pruebe con “10.00” … para eliminar este error, quiero agregar una pequeña solución al convertir cadenas en palabras, int indexOfDecimal = value.indexOf(“.”); Cadena decimal = valor.subcadena(indexOfDecimal + 1, valor.longitud()); BigDecimal decimalValue = new BigDecimal(decimal); if (decimalValue.compareTo(BigDecimal.ZERO) == 0) value = value.substring(0, indexOfDecimal);
– Abhishek Chatterjee
12 de noviembre de 2013 a las 11:30
Creo que esta solución no es la mejor, ya que solo funciona para intpero creo que es genial para un principiante.
public class NumberWordConverter {
public static final String[] units = {
"", "one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
};
public static final String[] tens = {
"", // 0
"", // 1
"twenty", // 2
"thirty", // 3
"forty", // 4
"fifty", // 5
"sixty", // 6
"seventy", // 7
"eighty", // 8
"ninety" // 9
};
public static String convert(final int n) {
if (n < 0) {
return "minus " + convert(-n);
}
if (n < 20) {
return units[n];
}
if (n < 100) {
return tens[n / 10] + ((n % 10 != 0) ? " " : "") + units[n % 10];
}
if (n < 1000) {
return units[n / 100] + " hundred" + ((n % 100 != 0) ? " " : "") + convert(n % 100);
}
if (n < 1000000) {
return convert(n / 1000) + " thousand" + ((n % 1000 != 0) ? " " : "") + convert(n % 1000);
}
if (n < 1000000000) {
return convert(n / 1000000) + " million" + ((n % 1000000 != 0) ? " " : "") + convert(n % 1000000);
}
return convert(n / 1000000000) + " billion" + ((n % 1000000000 != 0) ? " " : "") + convert(n % 1000000000);
}
public static void main(final String[] args) {
final Random generator = new Random();
int n;
for (int i = 0; i < 20; i++) {
n = generator.nextInt(Integer.MAX_VALUE);
System.out.printf("%10d = '%s'%n", n, convert(n));
}
n = 1000;
System.out.printf("%10d = '%s'%n", n, convert(n));
n = 2000;
System.out.printf("%10d = '%s'%n", n, convert(n));
n = 10000;
System.out.printf("%10d = '%s'%n", n, convert(n));
n = 11000;
System.out.printf("%10d = '%s'%n", n, convert(n));
n = 999999999;
System.out.printf("%10d = '%s'%n", n, convert(n));
n = Integer.MAX_VALUE;
System.out.printf("%10d = '%s'%n", n, convert(n));
}
}
La prueba crea 20 números aleatorios hasta Integer.MAX_VALUE y que algunos que saben que son problemáticos, por 0, 10, etc. Salida:
5599908 = 'five million five hundred ninety nine thousand nine hundred eight'
192603486 = 'one hundred ninety two million six hundred three thousand four hundred eighty six'
1392431868 = 'one billion three hundred ninety two million four hundred thirty one thousand eight hundred sixty eight'
1023787010 = 'one billion twenty three million seven hundred eighty seven thousand ten'
1364396236 = 'one billion three hundred sixty four million three hundred ninety six thousand two hundred thirty six'
1511255671 = 'one billion five hundred eleven million two hundred fifty five thousand six hundred seventy one'
225955221 = 'two hundred twenty five million nine hundred fifty five thousand two hundred twenty one'
1890141052 = 'one billion eight hundred ninety million one hundred forty one thousand fifty two'
261839422 = 'two hundred sixty one million eight hundred thirty nine thousand four hundred twenty two'
728428650 = 'seven hundred twenty eight million four hundred twenty eight thousand six hundred fifty'
860607319 = 'eight hundred sixty million six hundred seven thousand three hundred nineteen'
719753587 = 'seven hundred nineteen million seven hundred fifty three thousand five hundred eighty seven'
2063829124 = 'two billion sixty three million eight hundred twenty nine thousand one hundred twenty four'
1081010996 = 'one billion eighty one million ten thousand nine hundred ninety six'
999215799 = 'nine hundred ninety nine million two hundred fifteen thousand seven hundred ninety nine'
2105226236 = 'two billion one hundred five million two hundred twenty six thousand two hundred thirty six'
1431882940 = 'one billion four hundred thirty one million eight hundred eighty two thousand nine hundred forty'
1991707241 = 'one billion nine hundred ninety one million seven hundred seven thousand two hundred forty one'
1088301563 = 'one billion eighty eight million three hundred one thousand five hundred sixty three'
964601609 = 'nine hundred sixty four million six hundred one thousand six hundred nine'
1000 = 'one thousand'
2000 = 'two thousand'
10000 = 'ten thousand'
11000 = 'eleven thousand'
999999999 = 'nine hundred ninety nine million nine hundred ninety nine thousand nine hundred ninety nine'
2147483647 = 'two billion one hundred forty seven million four hundred eighty three thousand six hundred forty seven'
@Test
public void given_a_complex_number() throws Exception {
assertThat(solution(1234567890),
is("one billion two hundred thirty four million five hundred sixty seven thousand eight hundred ninety"));
}
Dawud ibn Karim
/**
This Program will display the given number in words from 0 to 999999999
@author Manoj Kumar Dunna
Mail Id : [email protected]
**/
import java.util.Scanner;
class NumberToString
{
public enum hundreds {OneHundred, TwoHundred, ThreeHundred, FourHundred, FiveHundred, SixHundred, SevenHundred, EightHundred, NineHundred}
public enum tens {Twenty, Thirty, Forty, Fifty, Sixty, Seventy, Eighty, Ninety}
public enum ones {One, Two, Three, Four, Five, Six, Seven, Eight, Nine}
public enum denom {Thousand, Lakhs, Crores}
public enum splNums { Ten, Eleven, Twelve, Thirteen, Fourteen, Fifteen, Sixteen, Seventeen, Eighteen, Nineteen}
public static String text = "";
public static void main(String[] args)
{
System.out.println("Enter Number to convert into words");
Scanner sc = new Scanner(System.in);
long num = sc.nextInt();
int rem = 0;
int i = 0;
while(num > 0)
{
if(i == 0){
rem = (int) (num % 1000);
printText(rem);
num = num / 1000;
i++;
}
else if(num > 0)
{
rem = (int) (num % 100);
if(rem > 0)
text = denom.values()[i - 1]+ " " + text;
printText(rem);
num = num / 100;
i++;
}
}
if(i > 0)
System.out.println(text);
else
System.out.println("Zero");
}
public static void printText(int num)
{
if(!(num > 9 && num < 19))
{
if(num % 10 > 0)
getOnes(num % 10);
num = num / 10;
if(num % 10 > 0)
getTens(num % 10);
num = num / 10;
if(num > 0)
getHundreds(num);
}
else
{
getSplNums(num % 10);
}
}
public static void getSplNums(int num)
{
text = splNums.values()[num]+ " " + text;
}
public static void getHundreds(int num)
{
text = hundreds.values()[num - 1]+ " " + text;
}
public static void getTens(int num)
{
text = tens.values()[num - 2]+ " " + text;
}
public static void getOnes(int num)
{
text = ones.values()[num - 1]+ " " + text;
}
}
Lakh y Crore se usan en inglés indio, pero no en Europa ni en América. Ver Wikipedia.
– CoperNick
28 de noviembre de 2012 a las 17:12
¿Ha sido útil esta solución?
Tu feedback nos ayuda a saber si la solución es correcta y está funcionando. De esta manera podemos revisar y corregir el contenido.
Esta web utiliza cookies propias y de terceros para su correcto funcionamiento y para fines analíticos y para mostrarte publicidad relacionada con sus preferencias en base a un perfil elaborado a partir de tus hábitos de navegación. Al hacer clic en el botón Aceptar, acepta el uso de estas tecnologías y el procesamiento de tus datos para estos propósitos.
Configurar y más información
Aquí está la herramienta en línea que podría serle útil: helloacm.com/tools/convert-arabic-numerals-to-english-words
– justyy
7 mayo 2017 a las 17:00
Esto podría ser útil stackoverflow.com/questions/3911966/…
– Bu Said
12 de noviembre de 2020 a las 21:41