Rounding issues


(David Tomasheski) #1

I have a watch that performs an average on a value. I would like to round it to two decimal places. For some reason when I put the script in to round the result is wrong, plus it doesn't even round. In the below code avt_tv comes out to 1114.873063170441 while avg_tv_round comes out to 560.9466266866567. What am I doing wrong?

"aggs": {
        "avg_tv_round": {
          "avg": {
            "script": {
              "inline": "Math.round(doc['TESTVALUE'].value * 100.0)/100.0"
        "avg_tv": {
          "avg": {
            "field": "TESTVALUE"

(David Tomasheski) #2

So I figured out why one of my issues is happening. The avt_tv_round is dfferent because I have entries without the TESTVALUE field. According to the document I read on the avg aggreation missing values are supposed to be ignored but it seems that it is still counting those entries into the count for the avg divisor i.e. 3 of my 4 entries have TESTVALUE but after adding them together it divides by 4 instead of 3.

(Alexander Reelsen) #3

You could circumvent this using a value script as you have to specify a field, see

However scripting still means, that a script has to be executed for every document that is found, so just using this for rounding is highly inefficeent. Might be less resource intensive to just do this on the client side.

(David Tomasheski) #4

That circumvented the incorrect average problem but still the other problem the fact that it isn't rounding the result my updated code is below. Is there perhaps some setting I need to set in the elasticsearch.yml that I am unaware of? Or is it possible to round in the condition field(i tried but keep getting null back)

"avg_tv_round" : {
        "avg" : {
            "field" : "TESTVALUE",
            "script" : {
                "lang": "painless",
                "inline": "Math.round(_value * params.convertor)/params.convertor",
                "params" : {
                    "convertor" : 100.0

(Alexander Reelsen) #5


you could use NumberFormat/DecimalFormat to format, but this also converts to a string and you need to return a number here, because the average still needs to be calculated (which will be skewed as well).


(system) #6

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