Number to ordinal suffix

    0

    0

    Giovanny Gongora

    Codiga's TypeScript Recipes

    Takes a number and returns it as a string with the correct ordinal indicator suffix.

    const toOrdinalSuffix = (num: string) => {
      const int: number = parseInt(num),
        digits: number[] = [int % 10, int % 100],
        ordinals: string[] = ['st', 'nd', 'rd', 'th'],
        oPattern: number[] = [1, 2, 3, 4],
        tPattern: number[] = [11, 12, 13, 14, 15, 16, 17, 18, 19];
      return oPattern.includes(digits[0]) && !tPattern.includes(digits[1])
        ? int + ordinals[digits[0] - 1]
        : int + ordinals[3];
    };
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    Legal
    • Security
    • Privacy Policy
    • Code Privacy
    • Terms of Service
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.