Specify the number of decimal places on an aggregate average

Within my input on one of my watches I have :

"aggs": {
            "e2e_av_time": {
              "avg": {
                "field" : "e2e_time"
              }
            }

(Note that e2e_time is a long within my mapping.)
I then use it later in the action:
> "text": "The average e2e time has dropped to {{ctx.payload.aggregations.e2e_av_time.value}}ms"

However in some cases this is producing 8 decimal places from whole integer numbers. Simulation Output:

"text": "The average e2e time has dropped to 313.922512715544ms"`

The maximum number of decimal places I would want is 2 and preferably none! In order to fix this I tried to use a script :

"aggs": {
            "e2e_av_time": {
              "avg": {
                "script": {
                  "inline": "return (int) Math.ceil(doc['e2e_time'].value)"
                }
              }
            }
          }

I have also tried variations without casting and with Math.round() and .round(). I'm hoping that someone can tell me where I'm going wrong? Am i pointing to the wrong area of the payload? Thanks in advance.

Hey,

you can use DecimalFormat to format numbers properly. The correct position to do this, should be in a transform before your action is executed, do not do this as a script in your search, as this will decrease performance.

new java.text.DecimalFormat('#.##').format(3.151429)

Hope this helps!

--Alex

1 Like

Thanks for your help. How is this used within transform? Like a script? Could you give me an example transform using this decimal format?

Sorry for not being clear. I was referring to a script transform where you return a formatted value .

--Alex

Thanks for your help!

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.