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

sqxo8psd  于 2023-01-18  发布在  其他
关注(0)|答案(2)|浏览(209)

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]

我需要做什么?

9w11ddsr

9w11ddsr1#

似乎round在您的版本中不可用。请升级jq或使用floor实现round

def round: . + 0.5 | floor;

用法示例:

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

mznpcxlj2#

我们可以使用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
]

相关问题