How can i round a Float?

Monkey Forums/Monkey Programming/How can i round a Float?

xzess(Posted 2011) [#1]
Hello,

can anybody tell me how to round a float to two zero's after comma?

I get a float like 0.3500000000000000000001 and want it 0.35

Thanks in advice


Darky(Posted 2011) [#2]
I just have a code for rounding under GLFW / MINGW but you must custome your modules/lang/lang.monkey for it :-/


Jesse(Posted 2011) [#3]
this should work(untested):
int((n+.005)*100)/100.0



xzess(Posted 2011) [#4]
works perfectly, thanks Jesse!

Function RoundFloat:Float(Value:Float)
return	int((Value+.005)*100)/100.0
End



ziggy(Posted 2011) [#5]
It will fail for netative numbers, and also does not take into account latest significative digit rounding. This is a slightly fixed version:

fixed:
Function RoundFloat:Float(value:Float)
	Local intermedio:int = (value + 0.005 * Sgn(value))*1000
	return	intermedio/1000.0
End
Function Main()
	Print RoundFloat(0.3555)
	Print RoundFloat(-0.355)
End


Obviously float rounding precision errors will be shown.


Jesse(Posted 2011) [#6]
should it be 100 not 1000? He needs it rounded to two fraction digits not three.

note also that neither of the formulas will be accurate on all platforms or compilers.