Hello community,
I’ve noticed something strange while trying to code an experience bar, which is filled, when a button is pressed (didn’t include the button).
As you can see, I’m trying to add a real number (fillingWidth (=25.6)) to the width of a rectangle (filling) and want to make it with every click bigger, till the size of 256 (size of the xp rectangle with the mainWindowsize of 320).
As you can see, sometimes there are strange sums.
At the beginning of my code, filling.width is 0 and fillingWidth = xp.width*0.1 (I want to make 10 steps, till it reaches the correct size).
Rectangle {
id: xp
width: gameWindow.width*0.8
height: parent.height
color: "black"
border.width: 1
property real fillingWidth: width*0.1
signal clicked
onClicked: {
console.log("filling.width: ", filling.width, " + fillingWidth: ", fillingWidth)
filling.width += fillingWidth
console.log(" = filling.width new: ", filling.width)
}
Rectangle {
id: filling
anchors {
left: parent.left
top: parent.top
bottom: parent.bottom
}
color: "green"
width: 0
onWidthChanged: {
// if maximum is reached. Maximum is the width of xp-rectangle
if (width === xp.width) {
console.log("You won!")
anim.running = true
}
if (width > xp.width) { resetAnim() }
}
}
}
// signal clicked is triggered by a button.
The Output looks like this:
qml: filling.width: 0 + fillingWidth: 25.6
qml: = filling.width new: 25.6
qml: filling.width: 25.6 + fillingWidth: 25.6
qml: = filling.width new: 51.2
qml: filling.width: 51.2 + fillingWidth: 25.6
qml: = filling.width new: 76.80000000000001
qml: filling.width: 76.80000000000001 + fillingWidth: 25.6
qml: = filling.width new: 102.4
qml: filling.width: 102.4 + fillingWidth: 25.6
qml: = filling.width new: 128
qml: filling.width: 128 + fillingWidth: 25.6
qml: = filling.width new: 153.6
qml: filling.width: 153.6 + fillingWidth: 25.6
qml: = filling.width new: 179.2
qml: filling.width: 179.2 + fillingWidth: 25.6
qml: = filling.width new: 204.79999999999998
qml: filling.width: 204.79999999999998 + fillingWidth: 25.6
qml: = filling.width new: 230.39999999999998
qml: filling.width: 230.39999999999998 + fillingWidth: 25.6
qml: = filling.width new: 255.99999999999997
So my question is: why is 51.2 + 25.6 = 76.800…01?
I know, I can do some workaround like this:
onClicked: filling.width = Math.min(xp.width, filling.width + xp.fillingWidth)
But that’s not the point of clean coding 🙂
Maybe you know, what the problem is and how I can solve this? Probably it has something to do with the multiplication?
Thank you very much!
Best,
Nina