Round float to decimal places?

Monkey Forums/Monkey Programming/Round float to decimal places?

wmaass(Posted 2011) [#1]
I found a function for BMax that worked well for me.
Function Round:Float(N:Float, DecimalPlaces:Int)
	Return Float(N * 10.0^DecimalPlaces) / 10.0^DecimalPlaces
End Function


I need something like this for Monkey. Tried this:
Function Round:Float(N:Float, DecimalPlaces:Int)
	Return Float(N * Pow(10.0,DecimalPlaces)) / Pow(10.0,DecimalPlaces)
End Function


But it just gives me an Int. Anyone have an idea?


muddy_shoes(Posted 2011) [#2]
I'm not sure why you're getting an Int from your function as it returns a Float for me, but aren't you missing a cast to Int in order to truncate the value?

Function Round:Float(N:Float, DecimalPlaces:Int)
	Return Float(Int(N * Pow(10.0,DecimalPlaces))) / Pow(10.0,DecimalPlaces)
End Function



wmaass(Posted 2011) [#3]
Ah, you are right, I was getting a float. That wasn't the problem but your version works like a charm. Thanks muddy.


muddy_shoes(Posted 2011) [#4]
No problem. If you're using this function a lot then you might want to test whether using Floor instead of the Int cast is faster on your target platform.


wmaass(Posted 2011) [#5]
I will check that for sure. I'm calling this function a lot.