muledataweavemulesoftanypoint-studio

How to format a number to Euros currency format in dataweave?


I have a number, let's say - 287901.45

I want to format it to the string - "287.901,45 EUR"

How to do this dynamically?

I'm currently doing the below

%dw 2.0
output application/json
 
fun formatEU(number) =
    number as String {format: "#,##0.00"} 
        replace "." with "[temp]" 
        replace "," with "." 
        replace "[temp]" with ","
 
var number = 287901.45
---
formatEU(number) as String ++ " EUR" 

Is there a better way to do this?


Solution

  • You can use a locale in the conversion to String so the format is automatically configured. For example the Spanish locale (es) has the right format for your output.

    Example:

    %dw 2.0
    output application/json
     
    fun formatEU(number) =
        number as String {format: "#,##0.00", locale:"es"} 
     
    var number = 287901.45
    ---
    formatEU(number) as String ++ " EUR" 
    

    Output:

    "287.901,45 EUR"