Search code examples
bashroundingfloorceil

bash: How to round/floor/ceiling non-decimals thousands number?


lets say I have this number here 100675

how to turn it into 101000

all the solution I have found on google are solving decimals number.


Solution

  • The bash shell is able to do calculations internally, such as with the following transcript:

    pax:~> for x in 100675 100499 100500 100999 101000; do
    ...:~>     ((y = (x + 500) / 1000 * 1000))
    ...:~>     echo "    $x becomes $y"
    ...:~> done
        100675 becomes 101000
        100499 becomes 100000
        100500 becomes 101000
        100999 becomes 101000
        101000 becomes 101000
    

    This statement, ((y = (x + 500) / 1000 * 1000)), first adds 500 to make the otherwise-truncating integer division by 1,000 into a rounding division, then re-multiplies it by 1,000.