How I can round digit on the last column to 2 decimal after a dot using JQ?
Depending on your build of jq, you may have access to some cstdlib math functions (e.g., sin
or cos
). Since you're on *nix, you very likely do. In my particular build, I don't seem to have access to round
but perhaps you do.
def roundit: .*100.0|round/100.0;["Name","Description","Result"],(.hits.hits[]._source | [.acb.item.name, .acb.item.description, (.value|roundit)]) | @csv
Fortunately, it could be implemented in terms of floor
which I do have access to.
def roundit: .*100.0 + 0.5|floor/100.0;
I would pass it to awk via pipeline:
jq -r '["Name","Description","Result"],(.hits.hits[]._source | [.acb.item.name,.acb.item.description,.value])|@csv' yourfile | awk 'BEGIN{ FS=OFS="," }NR>1{ $3=sprintf("%.2f",$3) }1'
The output:
"Name","Description","Result""Account Average Latency","Generate of last month",210.09"Profile Average Latency","Profile average latency of last month",370.21
Here is your current filter with minor reformatting:
["Name", "Description", "Result"], ( .hits.hits[]._source | [.acb.item.name, .acb.item.description, .value] )| @csv
Here is a filter which rounds the value column. Note we do this after the @csv
so that we have full control over the string
def round: # e.g. (split(".") + ["0"])[:2] # ["210","08691986891395"] | "\(.[1])000"[:3] as $x | [.[0], $x[:2], $x[2:3]] # ["210","08","6"] | map(tonumber) # [210,8,6] | if .[2] > 4 then .[2] = 0 | .[1] += 1 else . end # [210,9,0] | if .[1] > 99 then .[1] = 0 | .[0] += 1 else . end # [210,9,0] | ["\(.[0])", "00\(.[1])"[-2:]] # ["210","09"] | join(".") # 210.09; ( ["Name", "Description", "Result"] | @csv ), ( .hits.hits[]._source | [.acb.item.name, .acb.item.description, .value] | @csv | split(",") | .[-1] |= round | join(",") )
If this filter is in filter.jq
and the sample data is in data.json
then the command
$ jq -Mr -f filter.jq data.json
produces
"Name","Description","Result""Account Average Latency","Generate of last month",210.09"Profile Average Latency","Profile average latency of last month",370.21