Search code examples
smalltalkpharo

Round to Integer in Smalltalk


I am currently building my first stuff on Smalltalk and I have hit an issue. I have to deal with a user-entered number, and I need to div it by 2 and still be an integer. If an user inputs 10, I will work with 5, if they input 11, I have to work with 6, but I will obviously get 5.5.

If I could get the mod of a number I could simply make sure mod = 0 else add 0.5 and it would do just as good, but I just can't find how to make a mod operation in SmallTalk, all my searches end up in unrelated stuff about actual social smalltalk, which is extremely frustrating.

So if you could tell me how to get the mod of a number it would be great, if you could tell me how to round up with a separate function, even better. Thanks for your help and time beforehand.

UPDATE: After some research, I tried to do it this way:

mod := par rem: 2.
mod = 0 ifFalse: [ par := par + 0.5 ].

where as "mod" is mod of the variable "par", and if it isn't 0, it should add up 0.5 to par.

My issue now is that trying to use par in a timesRepeat brings up a "BoxedFloat64 did not understand #timesRepeat" error. So I am still in the same issue, or just need a way to make a float into an integer.


Solution

  • There are a lot of ways. For example

    Add 1 to entered number before div by 2 if entered number is odd

    temp := enteredNumber.
    temp odd ifTrue: [temp := temp + 1 ].
    ^temp / 2 
    

    Using ceiling method

    ^(enteredNumber / 2) ceiling