Simple way to round

BlitzMax Forums/BlitzMax Programming/Simple way to round

JoshK(Posted 2008) [#1]
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.


Dreamora(Posted 2008) [#2]
strange as
function 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.


Digital Anime(Posted 2008) [#3]
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.


TomToad(Posted 2008) [#4]
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


Yan(Posted 2008) [#5]
BRL.Math could really do with a Round() function.


QuietBloke(Posted 2008) [#6]
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]