jq错误:在<top-level>处未定义round/0。

4

JQ中的round函数无法使用。

$ jq '10.01 | round'
jq: error: round/0 is not defined at <top-level>, line 1:
10.01 | round        
jq: 1 compile error

$ jq --help
jq - commandline JSON processor [version 1.5-1-a5b5cbe]

我需要做什么?
2个回答

6

看起来你的版本中没有提供round函数。你可以通过升级jq或使用floor函数来实现round函数:

def round: . + 0.5 | floor;

使用示例:

$ jq -n 'def round: . + 0.5 | floor; 10.01 | round'
10

0
我们可以使用pow函数和. + 0.5 | floor来创建自己的“round”函数,该函数以要舍入的值作为输入并以小数位数作为参数。
def round_whole:
  # Basic round function, returns the closest whole number
  # Usage:
  # 2.6 | round_whole // 3
  . + 0.5 | floor
;
def round(num_dec):
  # Round function, takes num_dec as argument
  # Usage: 2.2362 | round(2) // 2.24
  num_dec as $num_dec | 
  # First multiply the number by the number of decimal places we want to round to
  # i.e 2.2362 becomes 223.62
  . * pow(10; $num_dec) | 
  # Then use the round_whole function
  # 223.62 becomes 224
  round_whole |
  # Then divide by the number of decimal places we want to round by
  # 224 becomes 2.24 as expected
  . / pow(10; $num_dec)
;

jq --null-input --raw-output \
  '
    def round_whole:
      # Basic round function, returns the closest whole number
      # Usage:
      # 2.6 | round_whole // 3
      . + 0.5 | floor
    ;
    def round(num_dec):
      # Round function, takes num_dec as argument
      # Usage: 2.2362 | round(2) // 2.24
      num_dec as $num_dec |
      # First multiply the number by the number of decimal places we want to round to
      # i.e 2.2362 becomes 223.62
      . * pow(10; $num_dec) |
      # Then use the round_whole function
      # 223.62 becomes 224
      round_whole |
      # Then divide by the number of decimal places we want to round by
      # 224 becomes 2.24 as expected
      . / pow(10; $num_dec)
    ;
    [
      2.2362,
      2.4642,
      10.23423
    ] |
    map(
      round(2)
    )
  '

产出

[
  2.24,
  2.46,
  10.23
]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接