kuroko-lang / kuroko

Dialect of Python with explicit variable declaration and block scoping, with a lightweight and easy-to-embed bytecode compiler and interpreter.
https://kuroko-lang.github.io/
MIT License
431 stars 25 forks source link

Does Kuroko have an equivalent to Python's `round()` method? #48

Open kseistrup opened 8 months ago

kseistrup commented 8 months ago

[ Re: commit f1d7bdaa5a85cbba913495deb8f22c29ef0bca3e ]

I cannot seem to find a way to round a float to an int (or to a float with a given number of decimals), the way Python's round() does (and I ran into #47 when I tried to write a simple method that would round to an int).

I can see "round" referenced in the syn_py_types array in rline.c (line 910), but that seems to be related to Python, and not to Kuroko.

Am I missing something obvious?

If there is currently no way to round(number, ndigits=None) in Kuroko, please let this issue serve as an enhancement request.

:pray:

klange commented 8 months ago

There is currently no implementation of the builtin round function, nor is there a binding to the libm round function in the math module.

Some references for how Python does this:

klange commented 8 months ago

With the new functionality in float.__format__, you can now use it to implement decimal rounding through the f formatter. For example, to round to 5 decimal digits past the radix point, it should suffice to do float(n.__format__('.5f')). This is not dissimilar to what CPython does to implement float rounding.

To implement truncating behavior, you may pass a sufficiently large precision to __format__ to ensure all digits are represented without rounding (all floats are exactly representable in decimal, though it may take a precision of over 1000 to get all of the digits), and then cut the desired number of digits past the decimal point. Similarly for ceil behavior, you may examine all of the digits after the cut point and determine if any of them are non-zero.