【问题标题】:How to avoid exponent while converting a string to number in DataWeave 1.0如何在 DataWeave 1.0 中将字符串转换为数字时避免指数
【发布时间】:2019-09-20 05:51:07
【问题描述】:

我正在将存储在有效负载中的字符串“0.0000000”转换为 Data Weave 语言 1.0 中的数字

我试过 payload.Amount as :number

%dw 1.0
%output application/json
---
{
 Amount: payload.Amount as :number when payload.Amount != null
}

我期望最终输出为 0.0000000 但我得到的是 0E-7

【问题讨论】:

  • 小数点后零的个数不固定为7个,可能从0次到10次以上不等。例如0.0, 0, 0.00, 0.000000000000
  • 您能详细说明您的要求吗?比如数据来自哪里以及需要去哪里。您只需要正确的打印格式还是其他系统需要使用它?

标签: java mule dataweave


【解决方案1】:

我认为你的期望是错误的。根据RFC 4627,0E-7 是一个完全有效的 JSON 数字。任何正确的解析器都应该正确处理这个有效数字。与其他语言一样,数字在 JSON 中没有格式属性。只有当它们转换为字符串/从字符串转换时,才能应用格式。由于这些原因,您不能告诉 DataWeave 使用特定格式。

现在,如果您有一个使 0E-7 成为问题的特定问题,请更新说明以添加更多详细信息。

如果可以设置固定的小数位数,另一种可能可行的方法是调整https://help.mulesoft.com/s/article/How-to-force-DataWeave-to-return-Long-number 中描述的方法

例子

%dw 1.0
%output application/json
%function withZeroes(x)  x as :string { format: "#.####" } as :number
---
{
  Amount: withZeroes(0E-7),
  Amount2: withZeroes(0.000),
  Amount3: withZeroes(0.0001),
  Amount4: withZeroes(0.00001)
}

输出:

{
  "Amount": 0,
  "Amount2": 0,
  "Amount3": 0.0001,
  "Amount4": 0
}

【讨论】:

  • 我同意这是一个完全有效的数字,任何系统都应该接受它。这个数字 0E-7 正在被 PCF(Pivotal Cloud Foundry)上的其他服务消耗,并在那里抛出错误,因为 无效数字异常
  • 那是该服务使用的解析器的问题。它不能很好地处理边界情况。如果您不需要保留小数点右端的零,则有一个可能的解决方案。我会更新我的答案。
【解决方案2】:

您可能想要指定精度。类似的东西

as :number as :string {格式: "0.0000000"}

此处讨论的更多示例

https://help.mulesoft.com/s/article/How-to-format-numbers-in-DataWeave

【讨论】:

  • 我试过这个,它在引号中给出 "0.0000000" 但我需要最终输出为数字而不是字符串,不带引号。
【解决方案3】:

试试看

as :number as :number {格式:"#.#######"}

【讨论】:

    猜你喜欢
    • 2014-11-16
    • 2021-04-02
    • 1970-01-01
    • 2017-05-20
    • 2017-06-30
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 2020-06-20
    相关资源
    最近更新 更多