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

标签 arrays json csv unix 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
        }
      }
    ]
  }
}

我使用 JQ 来获取 csv 数据:
["Name","Description","Result"],(.hits.hits[]._source | [.acb.item.name,.acb.item.description,.value])|@csv

我看到结果:
"Name","Description","Result"
"Account Average Latency","Generate of last month",210.08691986891395
"Profile Average Latency","Profile average latency of last month",370.20963260148716

我有 210.08691986891395 和 370.20963260148716 但我想要 210.09 370.21

最佳答案

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

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

幸运的是,它可以按照 floor 来实现。我确实可以访问。
def roundit: .*100.0 + 0.5|floor/100.0;

关于arrays - 如何使用 JQ 在点后将最后一列的数字舍入到小数点后两位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46117049/

相关文章:

python - 如何将字节字符串拆分为单独的部分

jquery - Laravel 格式查询 json 结果

php - Sendgrid 邮件列表 ID

javascript - 遍历嵌套的 json 对象

csv - Netlogo 导出/Tableau 问题

javascript - 无法将 json 对象转换为二维数组

python - 如何将 numpy 数组保存到计算机中供以后在 python 中使用

c - 理解函数指针声明

python - 如何使用 pandas read_csv 函数有效处理欧洲小数点分隔符?

mysql - 使用 UTF-8 编码,具有特殊属性/外来字符的 CSV 文件在导入 MySQL (phpMyAdmin) 时未保留