Hello! I’m trying to make a KDR system. I only have 1 problem.
To make a KDR system, you need to divide the kills by the deaths, the only problem is, if a player had 18 kills, and 7 deaths, their KDR would be 2.571428571428571 you see the problem.
Instead of displaying that entire number, I only want to display 2.57. How would I go about doing this?
the KDR is displayed as “nan”, this is the code I have for testing purposes:
local player = game.Players.LocalPlayer
local kills = player:WaitForChild("Lifetime Kills").Value
local deaths = player:WaitForChild("Lifetime Deaths").Value
while true do
wait(.1)
KDR = tonumber(string.format("%.2f", kills / deaths))
print(KDR)
end
The reason why it’s printing back nan is cause that’s the term for “Not a Number”
This usually happens when you attempt to use a mathematical function on something that’s not supposed to be resulted back normally, like say “50 / 0” would be equal to nan
im not incredibly savvy when it comes to math but in most games when you have 0 deaths and a number of kills they just set your kd to how many kills you have. would it not make sense to do the same in this situation?
like (piggybacking off of @kiloe2’s code):
local Deaths = blah blah blah
local Kills = blah blah blah
local KDR = nil --(or 0)
while true do
if (Kills/Deaths) ~= 0 then
KDR = math.floor((Kills / Deaths) * 100) / 100
else
KDR = Kills
end
end
(i wrote this on my phone please let me know if there are any syntax errors)
Edit: added a while true do loop
Deaths will become current deaths OR 1, whichever is greater.
If deaths is 0, then it would load the value 1 instead (0 < 1)
Divide anything by itself and you will get the same value back.
2/1 = 1
12547/1 = 12547
x/1 = x
However, there is one issue in your example:
This is incorrect.
Dividing any number (except 0) will never give 0. For example: 1/1e10 = 0.00000…01 Only 0/x will result in 0.
You are still dividing by zero. The issue was that IF deaths == 0, then DON’T divide by zero.
Dividing kills/deaths will only be 0 if kills is zero. Otherwise it will be a fraction. And as I made clear you are still dividing by deaths even though it may be zero.
I hope it made sense, I had a bit of a hard time structuring this reply as there were three intertwined issues.