Since there isn't a specific MEL command for rounding floating point numbers to the nearest integer, we have to be a bit clever. Thanks to Julia Pakalns for a particularly elegant solution..
float $float = 3.14159265;
floor ( $float + 0.5 );
// Result: 3
And in Python? Just use the round() function:
float = 3.14159265
round ( float , 3)
# Result: 3.142 #
round ( float )
# Result: 3.0 #
round() is a built-in Python function, so no need to import anything from the math module.
OK, so now what about rounding a float to a given number of decimal places, in MEL ?
Bern asks "[...] can you please
ask for a 'rounding' function instead of having to write something such
as:
proc float round(float $val,float $dec){
$sign = `sign $val`;
float $dec = `pow 10 $dec`;
$val = (int) (($val + $sign*5/($dec*10)) * $dec);
$val = ($val / $dec);
return $val;
}
...each time i want to round a number" Well, Bern, one answer would be to use the python round() command, except you invoke it from MEL:
python ("round (100.555, 1)")
// Result: 100.6 //
Although this gets messy when you want to parse a MEL variable.
So my only other suggestion is to incorporate Julia's idea:
global proc float round(float $val,float $dec){
float $dp = `pow 10 $dec`;
$val = $val*$dp;
$val = `floor ($val + 0.5)`;
return ($val/$dp);
}
Save this procedure to a script called round.mel, put this in your user scripts directory and it'll be sourced automatically the next time you launch Maya.
Owen





Subscribe
instead of round(float) you can also typ int(float), but I guess float is better to use to have consistance.
regards
stefan
Posted by: Stefan Andersson | 15/09/2009 at 12:08 PM