Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

189
Visualizações
How can I format a number adding corresponding suffix to the end of it? - Java

I need in my text view to add a number, but also I need to add the corresponding suffix to that number like 1 is 1st, 2 is 2nd and so on. Is there any way to do this instead of writing a bunch of switch statements? The number is dynamic, so it doesn't have a range. Thank you.

Detailed description:

public String getNumberWithSuffix(int number) {
    /** Add an suffix to the end of the number, convert to string and return. 
        E.g. 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 Respostas
Responde à pergunta

0

Something like this -

// 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;
}

You can also make the map return an Optional to handle the null if needed.

If you are using Android, you can check this answer out - https://stackoverflow.com/a/49384322/4983469

over 4 years ago · Santiago Trujillo Relatório

0

Found an answer from similar question:-

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];

    }
}

Link - https://stackoverflow.com/a/6810409/8762338

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda