why my value keep decrease after reach the condition i set?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By potatobanana

here the problem,

i set my $Timer.wait_time to 0.1
then i decrease my c_cdvalue by 0.1 each 0.1second
but when i reach 0 my code should stop it from keep decreasing, but the last number reach zero always get -0 or -0.1. what wrong with my code and why it happend

var testSkill ={
  "skill1": {
	"name": "fire",
	"c_cd": 2.1,
	"percentage": 0
  },
  "skill2": {
	"name": "water",
	"c_cd": 3,
	"percentage": 0
  },
  "skill3": {
	"name": "wind",
	"c_cd": 0.9,
	"percentage": 0
  },
  "skill4": {
	"name": "earth",
	"c_cd": 0.5,
	"percentage": 0
  }
}


func _ready() -> void:
	print(DictCheck(testSkill))

func _unhandled_input(event: InputEvent) -> void:
	if event.is_action_pressed("mouse_L"):
		for x in testSkill.keys():
			print(testSkill[x].c_cd," = new print")

func _on_Timer_timeout() -> void:
	for x in testSkill.keys():
		if testSkill[x].c_cd >0:
			testSkill[x].c_cd -=0.1
		else:
			testSkill[x].c_cd = 0
			
		print(testSkill[x].c_cd)

	if DictCheck(testSkill) == true:
		$Timer.stop()
		print("passs")
	else:
		print("not passs")
	
func DictCheck(dict : Dictionary) -> bool:
	for item in dict:
		if dict[item]["c_cd"] > 0:
			return false
	
	return true

result

False
0
0.3
0.8
0.4
not passs
0
0.2
0.7
0.3
not passs
0
0.1
0.6
0.2
not passs
0
0
0.5
0.1
not passs
0
-0.1
0.4
0
not passs
0
0
0.3
-0.1
not passs
0
0
0.2
0
not passs
0
0
0.1
0
not passs
0
0
0
0
not passs
0
0
-0.1
0
passs
:bust_in_silhouette: Reply From: exuin

I think the answer might have to do with floating point imprecision. When you subtract by 0.1, you’re not really subtracting by 0.1, you’re subtracting by a number that’s really close to it. I copy-pasted your code and changed all the numbers to ints by multiplying by 10, which solved the issue.