#### Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

# How to turn a float into integer? (I mean remove the decimal, round the number, that kinda thing)

Posts: 121

Hellow! I have a class called square from last nights quick scratchpad project, and I intend to replace the individual square:touched(t) function with a faster function when using it on grops of squares

~~~
I was brainstorming, on the airplane i came up with this. As an example, if a square is 55x55, and theres 10 rows and columns, with 1,1 being the bottom left, then a touch at xy 70,120 should activate the square in row 3, column 2. This can be done with easy math on paper. Divide the touch x by width of a square to get the column, and touch y by height of a square for the row. Except I haven't really been able to test this theory out yet, and I still don't know how to handle multiple return values, but most important, I have no idea how to convert the decimal into an integer. Ok so basically I want to do this

70/55 gives, to approximate, 1 and 3/11, or column 2

120/55 gives ~ 2 and 2/11, set to row 3

Then return the id of the square located at that junction to the touched function and do whatever it is I want when a square is touched to happen, happen. Because before I was doing a for loop through all the squares which meant 100 square:touched calls and doing some math (if t.x < self.x + self.w, yadda yadda) for each square every time i touched the screen, I felt kinda dumb since this way its only one square that was actually touched. So the idea is to on touching the screen, call a function to divide the x,y of the touch by the w,h of the square, and then call only that one square.

• Posts: 42

Math.floor, string.format('%.0f"), etc. theres a plethora of options

• Mod
edited February 2017 Posts: 7,611

@xThomas Here's an example of what I think you're trying to do. Tap a square.

``````displayMode(FULLSCREEN)

function setup()
xSize,ySize=55,55
xGrid,yGrid=12,15
xPos,yPos=0,0
end

function draw()
background(0)
for x=1,xGrid do
for y=1,yGrid do
fill(255)
rect(x*xSize,y*ySize,xSize,ySize)
if x==xPos and y==yPos then
fill(255, 0, 0, 255)
rect(x*xSize,y*ySize,xSize,ySize)
fill(255)
text(xPos..","..yPos,xPos*xSize+xSize/2,yPos*ySize+ySize/2)
end
end
end
end

function touched(t)
if t.state==BEGAN then
xPos=math.floor(t.x/xSize)
yPos=math.floor(t.y/ySize)
if xPos<1 or xPos>xSize or yPos<1 or yPos>ySize then
xPos,yPos=0,0
end
end
end
``````