How can i round a Float?
Monkey Forums/Monkey Programming/How can i round a Float?
| ||
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 |
| ||
I just have a code for rounding under GLFW / MINGW but you must custome your modules/lang/lang.monkey for it :-/ |
| ||
this should work(untested):int((n+.005)*100)/100.0 |
| ||
works perfectly, thanks Jesse!Function RoundFloat:Float(Value:Float) return int((Value+.005)*100)/100.0 End |
| ||
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. |
| ||
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. |