• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 数字与度量衡国际化
2
3<!--Kit: Localization Kit-->
4<!--Subsystem: Global-->
5<!--Owner: @yliupy-->
6<!--Designer: @sunyaozu-->
7<!--Tester: @lpw_work-->
8<!--Adviser: @Brilliantry_Rui-->
9
10## 使用场景
11
12在不同的国家和文化中,数字、货币和度量衡的表示方法各异,包括小数分隔符、小数位数、货币和度量衡单位等。例如,应用界面需要显示数字“1,000”(一千)表示商品价格。若采用固定格式“1,000”,在欧洲某些国家(如德国)用户会将其理解为“1”,因为这些国家使用逗号作为小数分隔符。为了确保界面符合当地习惯,需要对数字、货币和度量衡进行格式化,使其根据用户的语言和地区设置显示。
13
14## 开发步骤
15
16### 数字格式化
17
18数字格式化请参考[Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat)19
20### 数字范围格式化
21
22数字范围格式化请参考[formatRange](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatRange)23
24### 货币和单位格式化
25
26货币和单位的格式化基于数字格式化,在创建货币和单位格式化对象时,将数字的显示风格分别设置为“currency(货币)”和“unit(单位)”。同样,对货币和度量衡进行格式化时也支持通过[Intl.NumberFormatOptions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options)设置不同的格式。
27
28### 度量衡转换
29
30度量衡包括长度单位、面积单位、体积单位和容量单位等,通过[I18NUtil](../reference/apis-localization-kit/js-apis-i18n.md#i18nutil9)类的[unitConvert](../reference/apis-localization-kit/js-apis-i18n.md#unitconvert9)接口实现度量衡转换和格式化。具体开发步骤如下:
31
321. 导入模块。
33   ```ts
34   import { i18n } from '@kit.LocalizationKit';
35   ```
36
372. 将度量衡从一个单位(fromUnit)转换到另一个单位(toUnit)。
38
39   将度量衡从fromUnit转换到toUnit,数值为value,并根据区域和风格格式化。style取不同值时,显示不同效果,详情见表1。
40   ```ts
41   let convertedUnit: string = i18n.I18NUtil.unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string);
42   ```
43
44**格式化风格**
45
46以fromUnit为美制单位cup,toUnit为公制单位liter,数字大小1000为例。
47
48**表1** 格式化使用的风格(style)
49
50| 取值 | 显示效果 |
51| -------- | -------- |
52| long | 236.588 liters |
53| short | 236.588 L |
54| narrow | 236.588L |
55
56**开发实例**
57
58```ts
59// 导入模块
60import { i18n } from '@kit.LocalizationKit';
61
62// 设置要转换的单位和目标单位
63let fromUnit: i18n.UnitInfo = {unit: 'cup', measureSystem: 'US'};
64let toUnit: i18n.UnitInfo = {unit: 'liter', measureSystem: 'SI'};
65
66// 以en-US区域ID转换度量衡
67let convertedUnit: string = i18n.I18NUtil.unitConvert(fromUnit, toUnit, 1000, 'en-US'); // convertedUnit = '236.588 L'
68
69// 显示完整的度量衡
70convertedUnit = i18n.I18NUtil.unitConvert(fromUnit, toUnit, 1000, 'en-US', 'long'); // convertedUnit = '236.588 liters'
71```
72