首页 > 解决方案 > 价格对象交易 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”),我们如何才能以正确的形式获得单位和纳米?

标签: actions-on-google

解决方案


您无需准确显示 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
    };
}

推荐阅读