Round down a number to its closest multiple of 3 using bash commands

Viewed 34

I have to round a number to its nearest least multiple of 3

For example:

For example:

n = 2939 => closest multiple of 3 is 2937
n = 3001 => closest multiple of 3 is 3000

Please suggest any commands to solve this.

I wonder if 'floor' command don't work in linux.

1 Answers

bash can only handle integers, which makes it easier here. Divide the number by 3 and multiply it by 3.

n=2939; x=$((n/3*3)); echo $x
n=3001; x=$((n/3*3)); echo $x

Output:

2937
3000
Related