Search code examples
formattingjq

how to round up to 2decimal in combination with %s in bash


Team, might be simple but am scratching head. if you see I am getting 0.00 instead of 59.42. also , I want to smartly set in the %.2f inside the first var itself so that I don't have to do it separately. any hint.

var="$(printf '%s' "$conditions" | jq -r 'select(.metricKey=="new_coverage").actualValue')"
echo $var
echo $var | printf "%.2f"
printf "%.2f" $var

output

echo $var
59.42028985507246
echo $var | printf "%.2f"
0.00printf "%.2f" $var

sample conditions is below

{ "status": "OK", "metricKey": "new_reliability_rating", "comparator": "GT", "periodIndex": 1, "errorThreshold": "1", "actualValue": "1" } { "status": "OK", "metricKey": "new_security_rating", "comparator": "GT", "periodIndex": 1, "errorThreshold": "1", "actualValue": "1" } { "status": "OK", "metricKey": "new_maintainability_rating", "comparator": "GT", "periodIndex": 1, "errorThreshold": "1", "actualValue": "1" } { "status": "ERROR", "metricKey": "new_coverage", "comparator": "LT", "periodIndex": 1, "errorThreshold": "80", "actualValue": "59.42028985507246" } { "status": "ERROR", "metricKey": "new_duplicated_lines_density", "comparator": "GT", "periodIndex": 1, "errorThreshold": "3", "actualValue": "18.823529411764707" }

Solution

  • Addressing OP's recent comments/questions about storing the %.2f results in var ...

    With the bash/printf builtin we can make use of the -v <variable> option, eg:

    $ printf -v var "%.2f" "59.42028985507246"
    
    $ typeset -p var
    declare -- var="59.42"
    

    Pulling the jq code into the mix:

    $ conditions='{ "status": "OK", "metricKey": "new_reliability_rating", "comparator": "GT", "periodIndex": 1, "errorThreshold": "1", "actualValue": "1" } { "status": "OK", "metricKey": "new_security_rating", "comparator": "GT", "periodIndex": 1, "errorThreshold": "1", "actualValue": "1" } { "status": "OK", "metricKey": "new_maintainability_rating", "comparator": "GT", "periodIndex": 1, "errorThreshold": "1", "actualValue": "1" } { "status": "ERROR", "metricKey": "new_coverage", "comparator": "LT", "periodIndex": 1, "errorThreshold": "80", "actualValue": "59.42028985507246" } { "status": "ERROR", "metricKey": "new_duplicated_lines_density", "comparator": "GT", "periodIndex": 1, "errorThreshold": "3", "actualValue": "18.823529411764707" }'
    
    $ printf -v var "%.2f" $(jq -r 'select(.metricKey=="new_coverage").actualValue' <<< "${conditions}")
    
    $ typeset -p var
    declare -- var="59.42"
    

    If printf -v is not available we could spawn an additional subprocess:

    $ var=$(printf "%.2f" $(jq -r 'select(.metricKey=="new_coverage").actualValue' <<< "${conditions}"))
    
    $ typeset -p var
    declare -- var="59.42"