Loading

How to format decimal numbers in DataWeave 2 for Mule 4

Date de publication: Mar 2, 2024
Tâche

GOAL

When converting a number to a string there is a need to specify how to handle the rounding method.
Étapes

Case 1: converting numbers to strings

In DataWeave numbers are formatted following the java.text.DecimalFormat class syntax. By default the rounding method used is HALF_EVEN. 

Example

%dw 2.0
output application/json
---
{
    noRounding: 123.456 as String,
    roundUp: 123.456 as String {format: "0.00"},
    roundEvenUp: 123.455 as String {format: "0.00"},
    roundDown: 123.454 as String {format: "0.00"}
}

Output

{
  "noRounding": "123.456",
  "roundUp": "123.46",
  "roundEvenUp": "123.46",
  "roundDown": "123.45"
}
You can select a different round mode by adding the roundMode attribute, and selecting one of the available modes from the Java class java.math.RoundingMode by name.
ModeDescription
CEILINGRounding mode to round towards positive infinity.
DOWNRounding mode to round towards zero.
FLOORRounding mode to round towards negative infinity.
HALF_DOWNRounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.
HALF_EVENRounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.
HALF_UPRounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
UNNECESSARYRounding mode to assert that the requested operation has an exact result, hence no rounding is necessary.
UPRounding mode to round away from zero.

Example

%dw 2.0
output application/json
---
{
    noRounding: 123.456 as String,
    roundDown: 123.456 as String {format: "0.00", roundMode:"DOWN"},
    roundHalfDown: 123.455 as String {format: "0.00", roundMode:"HALF_DOWN"},
    roundCeiling: 123.454 as String {format: "0.00", roundMode:"CEILING"}
}

Output

{
  "noRounding": "123.456",
  "roundDown": "123.45",
  "roundHalfDown": "123.45",
  "roundCeiling": "123.46"
}
As you can see the results are completely different with the same numbers, because of the different rounding options used.
Case 2: rounding numbers
At this time DataWeave doesn't provide functions to round numbers with decimals to a given precision. You can implement them easily as custom functions if needed.
Example
%dw 2.0
output application/json
fun roundDown(n,p) = do {
    var power = 10 pow p
    ---
    if (n>0) floor(n * power)/power
    else ceil(n * power)/power
}
---
{
    noRounding: 123.456,
    roundDown: roundDown(123.456,2)
}
Output
{
  "noRounding": 123.456,
  "roundDown": 123.45
}





 
Numéro d’article de la base de connaissances

001115993

 
Chargement
Salesforce Help | Article