如何使用 JQ 在点后将最后一列的数字舍入到小数点后两位?

Ser*_*g R 6 unix csv arrays json jq

如何将最后一列的数字四舍五入到小数点后两位?

我有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
        }
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

我使用 JQ 来获取 csv 数据:

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

我看到结果:

"Name","Description","Result"
"Account Average Latency","Generate of last month",210.08691986891395
"Profile Average Latency","Profile average latency of last month",370.20963260148716
Run Code Online (Sandbox Code Playgroud)

我有210.08691986891395和370.20963260148716但我想要210.09和370.21

Jef*_*ado 8

根据您的 jq 版本,您可能可以访问某些cstdlib 数学函数(例如,sin或cos)。既然你在 *nix 上,你很可能会这样做。在我的特定版本中,我似乎无法访问,round但也许您可以访问。

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

幸运的是,它可以按照floor我可以访问的方式实施。

def roundit: .*100.0 + 0.5|floor/100.0;
Run Code Online (Sandbox Code Playgroud)


Rom*_*est 0

我会通过管道将它传递给awk :

jq -r '["Name","Description","Result"],(.hits.hits[]._source |
       [.acb.item.name,.acb.item.description,.value])|@csv' yourfile | 
       awk 'BEGIN{ FS=OFS="," }NR>1{ $3=sprintf("%.2f",$3) }1'
Run Code Online (Sandbox Code Playgroud)

输出:

"Name","Description","Result"
"Account Average Latency","Generate of last month",210.09
"Profile Average Latency","Profile average latency of last month",370.21
Run Code Online (Sandbox Code Playgroud)