jq: error: round/0 is not defined at <top-level>
Asked Answered
J

2

4

round function in jq doesn't work.

$ 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]

What I need to do?

Janessa answered 14/6, 2019 at 7:35 Comment(0)
A
6

Seems like round is unavailable in your build. Either upgrade jq or implement round using floor:

def round: . + 0.5 | floor;

Usage example:

$ jq -n 'def round: . + 0.5 | floor; 10.01 | round'
10
Attlee answered 14/6, 2019 at 7:58 Comment(0)
C
0

We can use the pow function along with . + 0.5 | floor to create our own 'round' function that takes a value to round as input and the number of decimal places as argument.

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)
    )
  '

Yields

[
  2.24,
  2.46,
  10.23
]
Chromium answered 13/1, 2023 at 5:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.