albertodemichelis / squirrel

Official repository for the programming language Squirrel
http://www.squirrel-lang.org
MIT License
894 stars 148 forks source link

No Math Round method #244

Open ZackaryH8 opened 2 years ago

ZackaryH8 commented 2 years ago

Description of the problem

There is no easy way to round a number without using a lot of maths

Desired solution for the problem

A round method to be added to the math library

Additional context

https://forums.electricimp.com/t/round-float-to-fixed-decimal-places/2037/2

rversteegen commented 2 years ago

Quirrel added a round() function (but didn't document it...). It would be nice if it were added to Squirrel too, but I'm not sure just how small Alberto wants to keep the standard library.

The post you linked to incorrectly states that floor() returns an int. It actually returns a float. So to round x to nearest you just need to write math.floor(x + 0.5), you don't need to add * 1.0. That's not a lot of math, unless you want to round #.5 to even (or downwards) instead of upwards.

Also, that post is about rounding to a certain number of decimal places, but you never mentioned that, so we can assume you're not suggesting that. Because that would be a pretty kitchen-sink request which seems out of scope for the standard library.

ZackaryH8 commented 2 years ago

so we can assume you're not suggesting that

Yes you are correct, that link does not describe the solution wanted. To be clear the feature I would like is math.round() function which takes a number and behaves like it does in a language like JavaScript.

rversteegen commented 2 years ago

math.round() in Quirrel calls C's round(), which rounds #.5 away from 0.

Math.round() in JavaScript rounds #.5 upwards, equivalent to floor(x + 0.5)

Python 3 rounds #.5 to even.