actions-on-google - 价格对象交易 API 中的纳米十进制表示法通过以 0 开头的数字出错
问题描述
在交易 API 文档中:
https://developers.google.com/actions/reference/rest/Shared.Types/Price
它规定产品的价格必须以以下格式重新表示:
{
"currencyCode": string,
"units": string,
"nanos": number
}
nanos 代表价格中的小数点。所以 18.98 欧元将是:
{
"currencyCode": EUR,
"units": 18,
"nanos": 980000000
}
但问题就在这里。例如,我如何代表 18.07 欧元。我会说:
{
"currencyCode": EUR,
"units": 18,
"nanos": 070000000
}
但情况是,以 0 开头的数字不是大声的。所以我们有点卡在这里如何管理这个。
给定作为字符串的原始价格(例如“18.07”),我们如何才能以正确的形式获得单位和纳米?
解决方案
您无需准确显示 9 位数字。您只需要一个数字,当除以 10^9(或者当您将小数点向左移动 9 位时,如果您愿意),代表您需要的单位的小数部分。
所以你的例子可以写成
{
"currencyCode": "EUR",
"units": "18",
"nanos": 70000000
}
您无需指定使用的语言,但如果您在 JavaScript 中执行此操作,则可以使用类似这样的方法传递两个字符串(价格和货币代码)并返回 Price 对象:
function price( p, cc ){
// Split the string on a decimal point, if present
let pa = p.split(".");
let units = pa[0];
// If we had something after the decimal point, add enough 0s to
// make sure it represents nanos, then turn it into a number
// by parsing it as a base-10 integer.
let nanos = 0;
if( pa.length > 1 ){
let ns = pa[1]+"000000000";
ns = ns.substring(0,9);
nanos = parseInt( ns, 10 );
}
return {
currencyCode: cc,
units: units,
nanos: nanos
};
}
推荐阅读
- c# - 如何使用 FulltrustProcessLauncher 执行 powershell 命令
- gradle - 在根项目“gradle-tutorial”中找不到路径为“:projectA”的项目
- sql - 使用 UNION 动态循环/加入结果
- c# - 结合 2 个 .csv 文件以及按日期对不同时间格式的内容进行排序
- ssas - DAX 计算列使用 IF 来评估另一个表中的值
- r - 从多个不同的表中转置数据框上的列
- sql - 今天日期的 SQL IF 语句
- javascript - 如何将多个动态事件监听器包装成一个?
- javascript - 错误:无法获取未定义或空引用的属性“_ScriptLoaderTask”
- perl - 检查错误值时,while循环将找不到正则表达式