Simple way to round
BlitzMax Forums/BlitzMax Programming/Simple way to round
| ||
I don't know why this escaped me so long, but if you want to convert a float to an integer with rounding, just do this: local i:int local f:float f=0.635484 i=f+0.5 print i Kind of dumb, but I never really thought of it before. |
| ||
strange asfunction round:int(val:float) return int(val+0.5) end functio has been posted several times in the past ... unless I'm totally wrong even in a thread where you were active. |
| ||
local i:int local f:float f=0.635484 i=f+0.5 print i Rounding this way doesn't work all the time correctly. Try the following example to find out : Local i:Int Local f:Float f=2.4999999999999 i=f+0.5 Print i 2.4999999999999 should give 2, not 3 the only way to do this exact is to convert the result to text, get the first number behind the dot and if it's 0-4 then rounding should be down, else rounding should be up. |
| ||
2.49999999999 is close enough to 2.5 for most purposes. So you can avoid the time spent with a string conversion. However, it is still good to know if exact rounding is needed. Also good to know is that it doesn't work with negative numbers. Local i:Int Local f:Float f= -2.4 i=f+0.5 Print i Prints -1 when the correct answer is -2 |
| ||
BRL.Math could really do with a Round() function. |
| ||
TomToad Im not at my home PC so I cant try it but what if you did the following. f/abs(f) should give either 1 or -1 go one further and f/abs(2*f) should give 0.5 or -0.5 so I think you can do : i = f + (f / abs(f*2)) so you will either add or subtract 0.5 from f. (I think) [edit] duh ! or you can just do an if statement Local i:Int Local f:Float f= -2.4 if f < 0 then i=f-0.5 else i=f+0.5 end if Print i [/edit] |