How to round, floor, ceil, truncate
Some builds may lack those functions, but as far as I'm concerned floor
is widely available; so, you can implement them using it.
round/0
def round: . + 0.5 | floor;
ceil/0
def ceil: if . | floor == . then . else . + 1.0 | floor end;
trunc/0
def trunc: if . < 0 then ceil else floor end;
In jq 1.6 you have access to round/ceil/floor functions
$ echo '{"mass": 188.72}' | jq ' .mass | round '189$ echo '{"mass": 188.72}' | jq ' .mass | ceil '189$ echo '{"mass": 188.72}' | jq ' .mass | floor '188$
For jq 1.5, here is the hack
Round:
$ echo '{"mass": 188.42}' | jq ' .mass + 0.5 | tostring | split(".") | .[0] ' -r188
Ceiling(may have to add more 9999s to increase precision):
$ echo '{"mass": 188.42}' | jq ' .mass + 0.99999999 | tostring | split(".") | .[0] ' -r189
Floor:
$ echo '{"mass": 188.42}' | jq ' .mass | tostring | split(".") | .[0] ' -r188
jq's math builtins are enumerated in the Math section of the jq Manual. The current release is at https://stedolan.github.io/jq/manual/;links to earlier versions are at the top.
Note that both jq 1.5 and 1.6 have builtins named round
, ceil
, floor
and trunc
: they are all 0-arity filters.
E.g.
[5.52, 5.50, -5.52 ] | map(trunc)#=> [5,5,-5]
Earlier versions of jq have different sets of Math functions, e.g. jq 1.4 has floor
but not the other three.