I sometimes get requests to add functions to Console Calculator.  I have many functions built-in to CCalc, but of course many more could be imagined.  Therefor, I made it possible to define your own functions.  I previously posted a short list of a few useful functions one might define:  Useful Console Calculator functions.

I received a request today for a more advanced round() function.  CCalc already includes a round() function, and it always rounds to the nearest integer.  The request I received was to support rounding to a specified decimal place:

round(2.535) = 3
round(2.535, 1) = 2.5
round(2.535, 2) = 2.54

In CCalc, function names may be overloaded, similar to C++, such that round(x) is a different function from round(x,n) since they take different number of input arguments. Although round(x) is a built-in CCalc function, round(x,n) is not – so let’s define it!

round(x,n) = round(x*10^n)/(10^n)

This new round function will round the number x to the nearest n decimal places. Very nice!


Hawker · November 26, 2010 at 5:08 pm

This is indeed very useful. Many thanks.

I have never used a function in CC with 2 parameters before.
This doesn’t work exactly as expected with the “European decimal character” option selected.

> round(x,n) = round(x*10^n)/(10^n)
** ERROR: invalid argument: x.n **

The option appears to literally swap dot and comma before the input is parsed.
I think this is a bug and that the swapping should be done when parsing and only if the comma is a decimal separator, but not if it is a variable separator.

CCalc · November 26, 2010 at 5:32 pm

When you use european mode, you have to use the period instead of comma for everything. So try round(x.n) instead and it should work for you. I know it is a bit strange, but otherwise it is difficult to tell when a comma is used as a decimal separator or when it separates arguments in a function.

Brr · November 29, 2010 at 10:13 am

Great! Thanks a lot!

Hawker · November 30, 2010 at 6:34 pm

Yes, I realize now that you can’t have the same character for decimal separator and argument separator. But honestly I find the dot very awkward when used as the argument separator 🙂

One way of doing this is going the spreadsheet way.
They usually change the argument separator to ; (semicolon) when in european mode.

Hawker · November 30, 2010 at 6:46 pm

And the round(x,n) function of course works also with negative numer of decimals.
Rounding to the nearest hundred goes like this:
round(279,-2) = 300

Very nice 🙂

CCalc · November 30, 2010 at 7:03 pm

“They usually change the argument separator to ; (semicolon) when in european mode.”
Hmm… I didn’t know about that, I’m not very familiar with european standards in that regard. Unfortunately, I already use the semicolon to separate multiple entries in a single line.

Leave a Reply

Avatar placeholder

Your email address will not be published.