Skip to main content
gamedev.net
🔒 Locked 🤖 Godot

[web] PHP rounding question

Started by Eliia 6 replies 1.4k views
Original Post
Eliia
Eliia
So I am trying to calculate XP levels, every 1000 points. The code I have works, but my code is triggering at 500,1500, 2500 etc to go to the next level, rather than at 1000,2000, 3000 etc. I tested and found that when the xp hits 1500, the code triggers because the PHP round function rounds up. If you divide 1551 by 1000 yu get 1.51 and the round function says good enough - it's 2. $orig_result = round($orig_result); So what I'd like to know/see is some PHP code that will do this 1000/1000 = 1 2000/1000 = 2 etc... Thanks Eliia
dannielum
dannielum
try to use modula (%) operator instead. Like this:

if ($number%1000 == 0)
{
level ++;
}
www.dannylum.com/games_projects.html - My Game Projectswww.dannylum.com/D2DProject - My Open Source 2D Map Editor
Eliia
Eliia
Aha, thanks for the idea - I didn't get modulus to work, but I did think to use explode() and make the code work another way

if ($orig_xp) {
$orig_result = $orig_xp/$nxtLvl;
}
//$orig_result = round($orig_result);
$pieces = explode(".",$orig_result);
$orig_result = $pieces[0];

round() rounds up after 500, 1500 etc - explode() show the true value 0,1,2 etc until i hit the next 1000 mark.

Thanks
Eliia
Coward
Coward
While explode works, I think you'd be better of using floor().

Edit: Beaten to it..
Don't Temp Fate..
Eliia
Eliia
Thanks :) I never seen floor(), will look it up. Thanks for trying :) Explode rocks.

Eliia
kwackers
kwackers
You could also cast to an int.

intval(2000 / 1000);
(int)(2000 / 1000);

Explode is good, but you are using it where you shoudn't.
Verminox
Verminox
Quote:
Original post by kwackers
You could also cast to an int.

intval(2000 / 1000);
(int)(2000 / 1000);

Explode is good, but you are using it where you shoudn't.



That's a bad idea if you are working with negative integers as well. Then, it would be something like:
-2000 to -1000  => -2 XP-1000 to     0  => -1 XP    0 to  1000  =>  0 XP 1000 to  2000  =>  1 XP


So if you had -500 HP, then:
floor(-500/1000) = floor(-0.5) = -1;

While:
(int)(-500/1000) = (int)(-0.5) = 0;



Type casting just truncates the float by removing all digits after the decimal point, while floor() adjusts the number to the greatest integer not larger than the given number (a.k.a Rounding Down).
--------------------------------------Amaze your friends! Astound your family! Kennify your text!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.