SAP UI5 货币金额显示的格式化逻辑
  I7JaHrFMuDsU 2024年08月09日 30 0
git

先看一些实际的例子:

var oFormat = NumberFormat.getCurrencyInstance({
"currencyCode": false,
"customCurrencies": {
"BTC": {
"symbol": "\u0243",
"decimals": 3
}
}
});

oFormat.format(123.4567, "BTC"); // "Ƀ 123.457"

上面的例子,定义了一个名为 BTC 的自定义货币符号,同时用 decimals 指定小数点后的数位,以及货币符号的 unicode 编码值。

运行结果如下:

SAP UI5 货币金额显示的格式化逻辑

另一个例子:

var oFormat = NumberFormat.getCurrencyInstance({
"currencyCode": false,
"customCurrencies": {
"MyDollar": {
"isoCode": "USD",
"decimals": 3
},
"Bitcoin": {
"decimals": 2
}
}
});

// symbol looked up from global configuration
oFormat.format(123.4567, "MyDollar");
// "$123.457"

// no symbol available, custom currency key is rendered
oFormat.format(777.888, "Bitcoin"); // "Bitcoin 777.89"

我们来单步调试查看 format 函数的执行原理。

进入 Currency.js 的 formatValue 方法。

目标类型为 string 字符串,所以进入 case string 的分支:

*/
Currency.prototype.formatValue = function(vValue, sTargetType) {
var aValues = vValue;
if (vValue == undefined || vValue == null) {
return null;
}
if (this.oInputFormat) {
aValues = this.oInputFormat.parse(vValue);
}
if (!Array.isArray(aValues)) {
throw new FormatException("Cannot format currency: " + vValue + " has the wrong format");
}
if ((aValues[0] == undefined || aValues[0] == null) && this.bShowNumber) {
return null;
}
switch (this.getPrimitiveType(sTargetType)) {
case "string":
return this.oOutputFormat.format(aValues);
default:
throw new FormatException("Don't know how to format currency to " + sTargetType);
}
};

SAP UI5 货币金额显示的格式化逻辑

读取 EUR 对应的 digit 数位

所有的格式都存储在 LocaleData 里:

SAP UI5 货币金额显示的格式化逻辑

SAP UI5 货币金额显示的格式化逻辑

找不到 EUR 对应的 digit 值:

SAP UI5 货币金额显示的格式化逻辑

于是读取 default 配置。如果 default 配置也为空,就返回默认的 2.

SAP UI5 货币金额显示的格式化逻辑

default 值维护在此处:2

SAP UI5 货币金额显示的格式化逻辑

此处把 87 和 2 使用小数点分隔开,放到不同的变量里分别存储:

SAP UI5 货币金额显示的格式化逻辑

iDotPos = sNumber.indexOf(".");
if (iDotPos > -1) {
sIntegerPart = sNumber.substr(0, iDotPos);
sFractionPart = sNumber.substr(iDotPos + 1);
} else {
sIntegerPart = sNumber;
}

最终的格式化结果:87.20

SAP UI5 货币金额显示的格式化逻辑

看另一个例子:9.99999 EUR

SAP UI5 货币金额显示的格式化逻辑

这里 preserveDecimals 的值为 true,因此 9.99999 小数点后的五个 9,会被保留下来。

SAP UI5 货币金额显示的格式化逻辑

如果我们把 preserveDecimals 的值改为 false,

SAP UI5 货币金额显示的格式化逻辑

最后显示的值就四舍五入变成了 10.00:

SAP UI5 货币金额显示的格式化逻辑

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2024年08月09日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年04月12日   69   0   0 git命令
  TEZNKK3IfmPf   2024年04月19日   80   0   0 git部署
  TEZNKK3IfmPf   2024年06月14日   52   0   0 git
  TEZNKK3IfmPf   2024年04月26日   59   0   0 gitgithub
I7JaHrFMuDsU