Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can round digit on the last column to 2 decimal after a dot using JQ?

How I round digit on the last column to 2 decimal places?

I have json:

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 9,
    "successful": 9,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 2.575364,
    "hits": [
      {
        "_index": "my-2017-08",
        "_type": "log",
        "_id": "AV5V8l0oDDWj-VP3YnCw",
        "_score": 2.575364,
        "_source": {
          "acb": {
            "version": 1,
            "id": "7",
            "owner": "pc",
            "item": {
              "name": "Account Average Latency",
              "short_name": "Generate",
              "description": "Generate of last month"
            },
            "service": "gsm"
          },
          "@timestamp": "2017-07-31T22:00:00.000Z",
          "value": 210.08691986891395
        }
      },
      {
        "_index": "my-2017-08",
        "_type": "log",
        "_id": "AV5V8lbE28ShqBNuBl60",
        "_score": 2.575364,
        "_source": {
          "acb": {
            "version": 1,
            "id": "5",
            "owner": "pc",
            "item": {
              "name": "Profile Average Latency",
              "short_name": "Profile",
              "description": "Profile average latency of last month"
            },
            "service": "gsm"
          },
          "@timestamp": "2017-07-31T22:00:00.000Z",
          "value": 370.20963260148716
        }
      }
    ]
  }
}

I use JQ to get csv data:

["Name","Description","Result"],(.hits.hits[]._source | [.acb.item.name,.acb.item.description,.value])|@csv

I see result:

"Name","Description","Result"
"Account Average Latency","Generate of last month",210.08691986891395
"Profile Average Latency","Profile average latency of last month",370.20963260148716

I have 210.08691986891395 and 370.20963260148716 but I want 210.09 and 370.21

like image 416
Serg R Avatar asked Sep 08 '17 12:09

Serg R


1 Answers

Depending on your build of jq, you may have access to some cstdlib math functions (e.g., sin or cos). Since you're on *nix, you very likely do. In my particular build, I don't seem to have access to round but perhaps you do.

def roundit: .*100.0|round/100.0;
["Name","Description","Result"],
(.hits.hits[]._source | [.acb.item.name, .acb.item.description, (.value|roundit)])
    | @csv

Fortunately, it could be implemented in terms of floor which I do have access to.

def roundit: .*100.0 + 0.5|floor/100.0;
like image 155
Jeff Mercado Avatar answered Sep 18 '22 00:09

Jeff Mercado