Notifications
Clear all

[Closed] number rounding

Seems that whenever I divide an integer by an integer to get an integer with maxscript, the result will always be rounded down. Or I’m guessing that the float values are just dropped off rather than any rounding going on. Is there an automatic way to do rounding? I’ve written little bits of script in the past that figure out what the difference between the result and the result as integer and if the value was about .5 then it rounded the resulting integer up etc… but is there a way to avoid having to do manual rounding everytime I want to deal with this kind of thing?

Cheers,

Cg.

4 Replies

Floor and Ceiling are the maxscript commands which round.

[left]ceil <number>[/left]

[left]Returns the nearest whole number greater than or equal to number. The result is always a float.[/left]

[left]floor <number>[/left]

[left]Returns the nearest whole number less than or equal to number. The result is always a float.
[/left]

[left]You’ll need to define the equation as float however if you’re using integers i.e.[/left]

[left]

[/left]
[left]a = 2[/left]
[left]b = 27[/left]
[left]d = b/a -- equals 13[/left]
[left]d = b/a as float -- equals 13.5[/left]
[left]c_a = ceil (b/a) as integer -- equals an integer 13 because the b/a operation returned an integer 13.[/left]
[left]c_b = ceil (b/a as float) as integer -- equals an integer 14 else will equal a float without "as integer"[/left]
[left]f = floor (b/a as float) as integer-- equals 13[/left]
[left]

[/left]

When you divide an integer by an integer, there are no float values at all and the result is truncated. This is normal integer division. Convert the integers to floats before you divide and you get a float. You can then round that with:

fn roundInt n = (n+0.5) as integer

Thanks both of you for the help.

I’m so greatful for the CGtalk maxscript forum.

I’d be lost without it. Learing maxscript would have been a lot slower and more painful without it.

Thanks everyone for everything so far.

Cg.

BTW Chris an easy way to get around this ‘my answer is an integer’ problem is to multiply by 1.0

ie:


5/2
2
 
5*1.0/2
2.5

There is a note in the help under the UI control progress bar about this

Cheers,

Josh.