skip to Main Content

How to add suffix like "st", "nd", or "rd" depending on number in JSONata?

I want to achieve something like this:

  • If number is 1, output "1st"
  • If number is 2, output "2nd"

2

Answers


  1. You can use conditionals and then string concatenation like shown in the example code below.

    $number := 2; // Replace with your number
    $lastDigit := $number % 10;
    $lastTwoDigits := $number % 100;
    (
      ($lastTwoDigits >= 11 and $lastTwoDigits <= 13) ? $number & 'th' : 
      ($lastDigit = 1 ? $number & 'st' : 
      ($lastDigit = 2 ? $number & 'nd' : 
      ($lastDigit = 3 ? $number & 'rd' : $number & 'th')))
    )
    
    Login or Signup to reply.
  2. You can declare this custom function on top of your JSONata expression and use it like so:

    (
      $toOrdinalNumber := function($number) {
        (
          $suffixes := ["th", "st", "nd", "rd"];
          /* for numbers > 100 */
          $remainder1 := $number % 100;
          /* for numbers < 100 */
          $remainder2 := $remainder1 % 10;
          /* special cases for 11, 12, 13 */
          $suffix1 := $remainder1 >= 11 and $remainder1 <= 13 ? "th";
          $suffix2 := $suffixes[$remainder2];
          /* 1. If suffix1 isn't null, return it.
            2. If suffix2 isn't null, return it instead.
            3. If both possible suffixes aren't available,
            safely assume the ordinal number ends with 'th'. */
          $finalSuffix := $exists($suffix1)
            ? $suffix1
            : $exists($suffix2)
              ? $suffix2
              : $suffixes[0];
          /* convert number to string and attach suffix */
          $string($number) & $finalSuffix
        )
      };
      /* call the custom function anywhere in your expression below */
      {
        '1': $toOrdinalNumber(1), /* 1st */
        '51': $toOrdinalNumber(51), /* 51st */
        '83': $toOrdinalNumber(83), /* 83rd */
        '111': $toOrdinalNumber(111), /* 111th */
        '123': $toOrdinalNumber(123), /* 123rd */
        '145': $toOrdinalNumber(145) /* 145th */
      }
    )
    

    Playground link: https://jsonatastudio.com/playground/4e1ae089

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search