Richie
Richie

Reputation: 5197

Dataweave Always output JSON number with two decimal places

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

Upvotes: 0

Views: 5629

Answers (4)

zachcdr
zachcdr

Reputation: 51

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: "#.##"}

Upvotes: 0

Ethan Port
Ethan Port

Reputation: 166

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.

Upvotes: 0

user1616423
user1616423

Reputation: 15

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.

Upvotes: 0

Yevgeniy
Yevgeniy

Reputation: 2694

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

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

Upvotes: 1

Related Questions