Rounding function for bc

bc doesn’t include a way to round floating point values to the nearest integer, but you can write one yourself. Just type this in:

define round(n)
{
    oldscale = scale
    if (n > 0)
        value = n + 0.5
    if (n < 0)
        value = n - 0.5
    scale = 0
    rounded = value / 1
    scale = oldscale
    return rounded
}

If you don’t feel like typing this in every time, you can add it to a file that will be loaded when you start bc. Type it into a file, such as $HOME/.bcrc and then add the following to your .bashrc file:

export BC_ENV_ARGS="$HOME/.bcrc"

Advertisements
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

2 Responses to Rounding function for bc

  1. John says:

    Nice.

    Add ‘auto oldscale’ and ‘auto rounded’ at the beginning to avoid polluting the variable namespace outside of the function.

    Replace ‘value’ with ‘n’. And ’rounded’ with ‘n’. And just use ‘return(n)’. If you do those things, you don’t need ‘auto value’ and ‘auto rounded’.

    Change ‘return x’ to ‘return(x)’ to avoid problems if non-paren gnu-ish extension is not supported. Similar reasoning: nestle opening curly on same line as ‘define’.

    Efficiency nit: change second ‘if’ to ‘else if’.

  2. John says:

    Add this to .bcrc for floating point modulo:

    define fmod(x,y) { auto oldscale; oldscale=scale; scale=1000; x=x-y*round(x/y); scale=oldscale; return(x); }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s