arnpry
arnpry

Reputation: 1141

Round Numerical Values to Nearest Multiple of 5

I have a text file with one line of percentages. I need to round all of the numbers in the text file to the nearest integer of 5, for example...

4 rounds up to 5, 8 rounds up to 10, 12 rounds down to 10, 17 rounds down to 15, etc...

Text File:

25% 80% 22% 67% 45% 30%

Expected Rounded Output:

25% 80% 20% 70% 45% 30%

Attempted Code for a Single Integer:

m=23 | (( m /= 5, m *= 5 )) && echo $m

Upvotes: 2

Views: 2088

Answers (3)

123
123

Reputation: 11216

Could use perl sub with e to evaluate expression in the replacement.

perl -pe 's{(\d+)(?=%)}{int(($1+2)/5)*5}ge' file

25,85%,20%,65%,45%,30,20%,2,10%

Upvotes: 1

anubhava
anubhava

Reputation: 785471

You can use this awk:

s='25% 80% 22% 67% 45% 30%'
awk '{for (i=1; i<=NF; i++) $i = int( ($i+2) / 5) * 5 "%"} 1' <<< "$s"

25% 80% 20% 65% 45% 30%

Upvotes: 2

Barmar
Barmar

Reputation: 781706

m / 5 always rounds down. You need to add 2 to the number before you divide so that it will get the closest number instead of the always round down.

m=23 ; (( m = (m+2)/5, m *= 5)); echo $m

Upvotes: 1

Related Questions