You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JSONata中根据数字添加st、nd或rd后缀?

在JSONata中为数字添加序数后缀的实现方法

可以通过结合JSONata的$mod、$in、$switch和$cond函数,实现根据数字自动添加st/nd/rd/th序数后缀的需求,核心表达式如下:

$string($) & 
  $cond(
    $in($mod($, 100), [11,12,13]), "th",
    $switch($mod($, 10), [
      [1, "st"],
      [2, "nd"],
      [3, "rd"],
      ["*", "th"]
    ])
  )

表达式说明

  • $string($):将当前处理的数字转换为字符串,为后续拼接后缀做准备
  • $mod($, 100):提取数字的最后两位,用于判断11、12、13这类特殊情况(无论前面的数字是什么,这三个数都使用th后缀)
  • $in(...):检查最后两位是否属于[11,12,13],若是则直接返回th
  • $switch(...):针对个位数字匹配对应的后缀:
    • 个位为1时返回st
    • 个位为2时返回nd
    • 个位为3时返回rd
    • 其他所有情况返回th

示例效果

  • 输入1 → 输出"1st"
  • 输入2 → 输出"2nd"
  • 输入3 → 输出"3rd"
  • 输入11 → 输出"11th"
  • 输入21 → 输出"21st"
  • 输入123 → 输出"123rd"

内容的提问来源于stack exchange,提问作者Shree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 22:28:10