Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

188
Vistas
¿Cómo puedo formatear un número agregando el sufijo correspondiente al final? -Java

En mi vista de texto, necesito agregar un número, pero también necesito agregar el sufijo correspondiente a ese número, como 1 es el primero, 2 es el segundo y así sucesivamente. ¿Hay alguna forma de hacer esto en lugar de escribir un montón de instrucciones de cambio? El número es dinámico, por lo que no tiene rango. Gracias.

Descripción detallada:

 public String getNumberWithSuffix(int number) { /** Add an suffix to the end of the number, convert to string and return. Eg the number is 1, the suffix needs to be 'st', so we concat them and return 1st. If the number is 2, the suffix needs to be 'nd', we concat them and return 2nd. The range is not specified so it can be any integer number. **/ }
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Algo como esto -

 // Initialize this as a singelton smwhere. Map<Integer, String> suffixMapper = new HashMap<Integer, String> suffixMapper.put(1, 'st'); suffixMapper.put(2, 'nd'); suffixMapper.put(3, 'rd');
 String getSuffix(int num) { if (num % 100 / 10 == 1) return "th" Integer lastDigit = num % 10 String suffix = suffixMapper.get(lastDigit) != null ? suffixMapper.get(lastDigit) : "th"; return suffix; }

También puede hacer que el mapa devuelva un Opcional para manejar el nulo si es necesario.

Si está utilizando Android, puede consultar esta respuesta: https://stackoverflow.com/a/49384322/4983469

over 4 years ago · Santiago Trujillo Denunciar

0

Encontré una respuesta de una pregunta similar: -

 public static String ordinal(int i) { String[] suffixes = new String[] { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" }; switch (i % 100) { case 11: case 12: case 13: return i + "th"; default: return i + suffixes[i % 10]; } }

Enlace: https://stackoverflow.com/a/6810409/8762338

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda