Search code examples
bashnumbersrounding

Bash round whole numbers up, down or to nearest hundreds


There is a range of whole positive numbers like

827818
6574762
685038
55326902

What I need, for example, to round down to hundreds to get accordingly

827800
6574700
685000
55326900

Many ideas how to round up, down or nearest hundreds using Javascript, for example

Math.floor(number / 100) * 100;

but is it possible to do the same in Bash ?


Solution

  • It's not entirely clear what is meant by "in Bash", but perhaps one of :

    $ cat input
    827818
    6574762
    685038
    55326902
    $ awk '{printf "%d00\n", $0 / 100}' input
    827800
    6574700
    685000
    55326900
    

    or (if all the values are greater than 100!):

    while read x; do echo "${x%[0-9][0-9]}00"; done < input
    

    If you want to handle the case where values are less than 100 and deal with negative values, you could do:

    while read x; do if test "${x#-}" -gt 100; then echo "${x%[0-9][0-9]}00"; else echo 0; fi; done < input
    

    but it's almost certainly better to stick with awk.