Dataweave Always output JSON number with two decim

2019-09-13 22:10发布

问题:

I've got the following number coming through via xml in Dataweave.

<b:AmountValue>180.90</b:AmountValue>

Using Dataweave I am trying to output a corresponding json number with two decimal places (to represent currency).

Here is what my Dataweave expression looks like...

amount: $.AmountValue as :number as :string {format: ".00"} as :number

The output json is losing the trailing zero.

i.e. "amount":180.9 

How can I change my Dataweave expression to always have two decimal places?

Or perhaps I'm misunderstanding the json number type?

thanks

回答1:

remote the last as :number if you can live with amount being a string

amount: $.AmountValue as :number as :string {format: ".00"}


回答2:

What happens if you put just amount: $.AmountValue as :number

I tried this on my preview of anypoint studio, and don't see losing the trailing 0. Also i am using the latest version.



回答3:

I also tested this and it works.

If you try this: 8.2 as :string {format: "0.00"} as :number

then the extra decimal place is added.

If you output to application/json or application/XML you'll see the two decimal places printed out 8.20. If you output to application/java, then it is a double, and you will have to decide how to print out the double.

If you try 8.2 as :number, then it prints out as 8.2.



回答4:

The coercion from from :string to :number, as previously stated, is what is dropping your trailing 0. Dataweave supports :number formatting dictated by use of an octothorp.

The below code snip will yield your required two decimal places.

 amount: $.AmountValue as  :number { format: "#.##"}