Neil24
Neil24

Reputation: 41

Mule dataweave: convert decimal to an integer

I want to convert a decimal (78.22) to an integer (78) using Dataweave.

<root>
<MoneyAmountRequired>78.22</MoneyAmountRequired>
</root>

I try as below and it doesn't work if I add default 0

moneyAmountRequired: payload.root.MoneyAmountRequired as :number{format: "0"} default 0 

Can some one please point out why it doesn't work when default 0 is present.

Thank you!

Upvotes: 2

Views: 8686

Answers (8)

Venu
Venu

Reputation: 19

Use floor function of dataweave.

{
    root: {
        MoneyAmountRequired: floor payload.root.MoneyAmountRequired
    }
}

Upvotes: 2

Zahid
Zahid

Reputation: 69

Use this for

%dw 1.0

%output application/json

{ value : moneyAmountRequired: floor payload.root.MoneyAmountRequired as :number default 0 }

Upvotes: -1

devmaker64
devmaker64

Reputation: 1

((payload.root.MoneyAmountRequired as :string) splitBy '.')[0] as :number

If you prefer to use a function, then:

%function truncateDecimals(d) ((d as :string) splitBy '.')[0] as :number when d != null otherwise d
---
{value: truncateDecimals(payload.root.MoneyAmountRequired)}

Upvotes: 0

devmaker64
devmaker64

Reputation: 1

After the number is formatted, it is indeed a string, but you are defaulting it to a number 0 instead of defaulting it to a string "0". But that would be enough if 'as :number' did not failed when the variable is null, which is in the first place the reason you need the default. Therefore, default it before converting it to a number as follows:

moneyAmountRequired: (payload.root.MoneyAmountRequired default "0") as :number{format: "0"}

Hope this will answer your question about the default 0 not working.

Upvotes: 0

himanshu
himanshu

Reputation: 21

Check this: %dw 1.0 %output application/java

%var regex = /(.\d+?)0+\b/

data replace regex with ""

Upvotes: 0

AnupamBhusari
AnupamBhusari

Reputation: 2415

This works for me.

moneyAmountRequired: payload.root.MoneyAmountRequired as :number {format: "##,##"} as :string {format: "##"} as :number

Hope this helps.

Upvotes: 0

Satheesh Kumar
Satheesh Kumar

Reputation: 797

Try myvalue: removeDecimal(28.23)

Upvotes: 0

Anirban Sen Chowdhary
Anirban Sen Chowdhary

Reputation: 8311

You can try the following :-

moneyAmountRequired: payload.root.MoneyAmountRequired as :string {format: "0"}as :number default 0

Here you need to convert it first in String as :string then in number as :number
This is the only way it seems to work !!
ref:- Mule Dataweave format :number

Upvotes: 0

Related Questions