Intl.PluralRules 实战:基数、序数、小数精度与范围的十个可运行例子

10-24 5阅读

多语言界面的数量文案,不能一直靠“等于一用单数,否则加字母”解决。Intl.PluralRules 做的是根据语言、数量类型与精度选择类别,再由你的文案资源决定使用哪个词或整句话。它不翻译名词,也不会自动生成英文序数后缀。把“选类别”和“写文案”拆开,才能避免把英语习惯硬套给其他语言。

本文在已安装的 Node.js 24.19.0 上逐段运行,ICU 为 78.3,CLDR 为 48.0,V8 为 13.6.233.17-node.51,测试日期为北京时间 2026 年 10 月 24 日。这些是本机环境记录,不代表各版本的发布日期,也不是浏览器兼容性承诺。十段代码都可单独保存为 .cjs 文件,再用 node 加文件名执行;每段带断言,下面的输出就是复现判据。

五个正例展示可采用的写法,五个反例则运行错误思路并断言它与正确结果不同,因此反例通过测试不等于错误写法正确。示例不依赖第三方包。若断言失败,先比较运行环境、语言数据与实际配置,不要直接把期望值改成当前输出。

Intl.PluralRules 实战:基数、序数、小数精度与范围的十个可运行例子
模型生成的概念示意图,并非软件截图。图中数字分组仅作视觉隐喻,不对应任何语言的实际类别规则;准确结果以正文代码为准。

先厘清两个维度:数量类型与语言类别

cardinal 用于“几个”的基数场景,也是默认类型;ordinal 用于“第几个”的序数场景。返回值来自 zero、one、two、few、many、other 这些语法选择标签,但某种语言并不一定使用全部标签。它们不等于待显示的译文,也不应机械等同于传统语法术语。CLDR 按数字变化引起的表达变化划分类别,官方说明也强调这种分类的边界。

正例一:用基数类别选择英文词形

先创建可复用的规则对象,再查文案表。这里把数字零、数字一和数字二放在一起测试,能顺便发现只检查一与二的测试遗漏。这个小词表只用于英语 file 这个名词,不是通用翻译器;换一个名词,就应更换资源,而不是修改类别算法。

const assert = require('node:assert/strict');
const rules = new Intl.PluralRules('en', { type: 'cardinal' });
const forms = { one: 'file', other: 'files' };
const result = [0, 1, 2].map(n => `${n} ${forms[rules.select(n)]}`);
assert.deepEqual(result, ['0 files', '1 file', '2 files']);
console.log(result.join(' | '));

本机实际输出:

0 files | 1 file | 2 files

正例二:序数必须明确指定 ordinal

同样的数字,在序数场景会命中不同分支。下面有意加入十一、十二、十三与二十一,避免一个只看个位数字的后缀函数看似有效。后缀表属于这个英文示例的表达策略,不能拿去给俄语或中文拼接;完整本地化还需要对应语言的文案设计。

const assert = require('node:assert/strict');
const rules = new Intl.PluralRules('en', { type: 'ordinal' });
const suffix = { one: 'st', two: 'nd', few: 'rd', other: 'th' };
const values = [1, 2, 3, 4, 11, 12, 13, 21];
const result = values.map(n => `${n}${suffix[rules.select(n)]}`).join(' ');
assert.equal(result, '1st 2nd 3rd 4th 11th 12th 13th 21st');
console.log(result);

本机实际输出:

1st 2nd 3rd 4th 11th 12th 13th 21st

正例三:比较英语、俄语与中文的基数结果

本例先确认三个语言标记获得支持,再打印本机报告的类别集合。每行箭头后的结果依次对应 0、1、2、5、21、1.2。俄语样本中的二十一落在 one,小数落在 other;中文 zh 的基数类别集合只有 other。这并不是“中文没有数量表达”,而是当前类别系统不要求在这里区分更多分支。

类别集合与选值结果一起断言,比仅断言一串译文更容易定位问题:前者检查语言数据和配置,后者检查实际数量分支。本文只展示有限样本,不把它当作各语言的完整语法表;需要规则全貌时查阅 CLDR 48 语言类别表。

const assert = require('node:assert/strict');
const locales = ['en', 'ru', 'zh'];
assert.deepEqual(Intl.PluralRules.supportedLocalesOf(locales), locales);
const values = [0, 1, 2, 5, 21, 1.2];
const expected = {
  en: ['one,other', 'other,one,other,other,other,other'],
  ru: ['one,few,many,other', 'many,one,few,many,one,other'],
  zh: ['other', 'other,other,other,other,other,other']
};
for (const locale of locales) {
  const rules = new Intl.PluralRules(locale);
  const categories = rules.resolvedOptions().pluralCategories.join(',');
  const selected = values.map(n => rules.select(n)).join(',');
  assert.deepEqual([categories, selected], expected[locale]);
  console.log(`${locale}: ${categories} => ${selected}`);
}

本机实际输出:

en: one,other => other,one,other,other,other,other
ru: one,few,many,other => many,one,few,many,one,other
zh: other => other,other,other,other,other,other

正例四:小数精度会参与类别选择

maximumFractionDigits 为零时,示例中的 1.2 按整数精度处理,英语结果从 other 变成 one。minimumFractionDigits 为一则保留一位小数精度,使数值一对应的结果变为 other。这里没有先改写原变量;规则对象根据选项完成自己的精度处理。

如果界面把 1.2 显示成 1,选词也应使用与显示匹配的精度,否则可能出现“1 files”。因此第二行让 NumberFormat 与 PluralRules 共享同一组小数选项。本例没有混用有效数字选项,也没有覆盖所有舍入模式;扩展这些配置时,应补充边界测试,而不是从一个小数推广全部行为。

const assert = require('node:assert/strict');
const base = new Intl.PluralRules('en');
const options = { maximumFractionDigits: 0 };
const rounded = new Intl.PluralRules('en', options);
const padded = new Intl.PluralRules('en', { minimumFractionDigits: 1 });
const result = [base.select(1.2), rounded.select(1.2), padded.select(1)];
assert.deepEqual(result, ['other', 'one', 'other']);
console.log(result.join(' | '));
const number = new Intl.NumberFormat('en', options);
const forms = { one: 'file', other: 'files' };
const text = `${number.format(1.2)} ${forms[rounded.select(1.2)]}`;
assert.equal(text, '1 file');
console.log(text);

本机实际输出:

other | one | other
1 file

正例五:范围类别单独检测、单独计算

本机确实提供 selectRange,因此这里先检查方法,再测试英语基数范围。它选择范围的语法类别,不负责格式化区间文本,也不负责遍历区间中的每个整数。下面比较单值一、零到一的范围、一到二的范围。第一种结果为 one,后两种为 other;单值方法和范围方法不能仅凭名称相近而互换。

缺少此方法的环境会在能力断言处明确停止,不能把端点规则伪装成通用降级实现。这里仅验证两个不等端点的具体范围,不把结果扩展到全部范围边界。产品若改变展示策略,也需要重新核对选词逻辑,而不是只改屏幕上的连接符。

const assert = require('node:assert/strict');
const rules = new Intl.PluralRules('en');
assert.equal(typeof rules.selectRange, 'function', 'selectRange required');
const result = [rules.select(1), rules.selectRange(0, 1), rules.selectRange(1, 2)];
assert.deepEqual(result, ['one', 'other', 'other']);
console.log(result.join(' | '));

本机实际输出:

one | other | other

反例一:把 n === 1 当作跨语言规则

错误函数把俄语的二十一分到 other,本机规则却返回 one。这里的差异足以否定这个通用化方案,无须手写并维护一套新的取模规则。业务只支持英语时也应写清语言范围,别给一个局部函数起“适用于所有语言”的名字。

const assert = require('node:assert/strict');
const n = 21;
const wrong = n === 1 ? 'one' : 'other';
const actual = new Intl.PluralRules('ru').select(n);
assert.equal(wrong, 'other');
assert.equal(actual, 'one');
assert.notEqual(wrong, actual);
console.log(`wrong=${wrong}; actual=${actual}`);

本机实际输出:

wrong=other; actual=one

反例二:拿默认基数规则拼序数

只准备正确后缀表仍然不够,默认类型会使数字二命中 other,拼出错误的 2th。修复点不是在结果上替换字符,而是在构造时选择正确的数量类型。类型、语言和选项应当共同构成缓存键,避免复用到另一种用途的对象。

const assert = require('node:assert/strict');
const suffix = { one: 'st', two: 'nd', few: 'rd', other: 'th' };
const wrong = `2${suffix[new Intl.PluralRules('en').select(2)]}`;
const right = `2${suffix[new Intl.PluralRules('en', { type: 'ordinal' }).select(2)]}`;
assert.equal(wrong, '2th');
assert.equal(right, '2nd');
console.log(`wrong=${wrong}; right=${right}`);

本机实际输出:

wrong=2th; right=2nd

反例三:直接把类别标签展示给读者

2 other 是程序标签泄漏,不是本地化结果。应使用类别去查资源;复杂句子可以按类别保存整句模板,而非只替换一个名词。other 也不是异常处理专用值,它在很多正常输入中就是正确分支,所以资源设计不能把它当作“未知错误”。

const assert = require('node:assert/strict');
const rules = new Intl.PluralRules('en');
const wrong = `2 ${rules.select(2)}`;
const forms = { one: 'file', other: 'files' };
const right = `2 ${forms[rules.select(2)]}`;
assert.equal(wrong, '2 other');
assert.equal(right, '2 files');
console.log(`wrong=${wrong}; right=${right}`);

本机实际输出:

wrong=2 other; right=2 files

反例四:以为字符串会保留输入尾零的语法效果

在本机默认规则下,字符串“1.0”和数值一得到同样的 one,不能通过加一个小数点来强迫规则采用固定小数位。要表达一位小数的精度意图,应明确传入 minimumFractionDigits。本例仅断言这些具体输入,不建议让未经验证的任意文本直接进入选词逻辑。

const assert = require('node:assert/strict');
const base = new Intl.PluralRules('en');
const explicit = new Intl.PluralRules('en', { minimumFractionDigits: 1 });
const result = [base.select('1.0'), base.select(1), explicit.select(1)];
assert.deepEqual(result, ['one', 'one', 'other']);
assert.notEqual(result[0], result[2]);
console.log(result.join(' | '));

本机实际输出:

one | one | other

反例五:用范围终点的类别冒充范围类别

下面计算从零到一的范围:终点一的类别为 one,但整个范围的类别为 other。差异证明“选终点即可”的算法不可靠,而不是证明范围永远返回 other。其他语言、类型与数值组合需要各自验证,不应照搬这个英语样本的输出。

const assert = require('node:assert/strict');
const rules = new Intl.PluralRules('en');
assert.equal(typeof rules.selectRange, 'function', 'selectRange required');
const wrong = rules.select(1);
const actual = rules.selectRange(0, 1);
assert.equal(wrong, 'one');
assert.equal(actual, 'other');
assert.notEqual(wrong, actual);
console.log(`endpoint=${wrong}; range=${actual}`);

本机实际输出:

endpoint=one; range=other

落地时检查什么

先确定语言与基数或序数,再设计类别到文案的映射;随后统一数字显示与类别计算的精度,并把零、十几、较大整数和小数纳入测试。涉及范围时单独检测能力,避免悄悄替换语义。升级运行时后重跑断言,并记录实际 resolvedOptions 与 ICU 数据版本,才能判断变化来自代码还是语言数据。

本教程验证的是上述本机样本,不宣称覆盖所有词形、所有语言或所有浏览器。Node 的国际化实现使用 ICU,构建和数据配置可能影响可用能力,部署检查可参考 Node.js 国际化文档。API 定义、选项处理和范围算法可对照 ECMA-402 第十二版 PluralRules 章节;本文没有假定在线草案中的新增功能已经出现在本机。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。