Inaccurate calculations - simple addition

I am very new to Velo and, having followed a number of tutorials, have just ventured into writing my very first piece of my own and am getting unexpected results.
My intention was to write a function which increments the opacity of a box each time it is clicked (simple I know!). The problem is not with the function itself, but with simple addition. I set a variable “opac” to an initial value of 0.1, then each time the box is clicked, the code should add 0.1 to “opac”. As a check, I am using console log to display the value of “opac” and these are the results:

0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999

How on earth can it get this wrong?

My code:

let opac = 0.1

export function Rect1_click(event) {

    opac = opac + 0.1;
    if (opac === 1) opac=0.1;
    console.log(opac);
    $w('#Rect1').style.backgroundColor = "rgba(105, 50, 110, " + opac + ")" ;
    
}

Hello. I would try toFixed(1) and see if the results are accurate enough for your needs. You can also google something like “adding decimals in Javascript” and you should see many results on how to approach this. Math is fun :slight_smile:

You can also continue with your code but calc the decimal itself:

let decimal = 1;
export function Rect1_click(event) {
    decimal++;
    if (decimal === 10) {decimal = 1;}
    console.log(decimal);
    $w('#Rect1').style.backgroundColor = "rgba(105, 50, 110, 0." + decimal + ")" ;
}

Oh I like this idea too! Thanks for offering another solution :grin:

Thank you both for your valuable advice. Both suggestions work great but, as a newbie, I’m amazed at how such a simple calculation can result in an inaccurate result. Every day is a school day :smile:
Thanks guys, I really appreciate you taking the time to help out a newbie.

JavaScript will level you occasionally for your entire career. And that’s what we are all here for! To keep learning together. Happy coding

This is actually an issue with Binary and not necessarily JavaScript. In binary decimal numbers are stored in what is known as BCD or Binary Coded Decimal values. This allows each digit to be assigned a fixed bit value. You can read more about that here: Binary-coded decimal - Wikipedia

0.1 can not accurately be converted into binary. Doing so gives us an infinite repeating number. You can see that represented below:

that line of numbers will repeat forever if allowed. (I.E. 0.000110001100011…)
This leaves us with a problem when converting back to decimal as we will never get exactly the same number that we are expecting.

You can read more about this here: Why 0.1 Does Not Exist In Floating-Point - Exploring Binary (also where I sourced the image)

Thanks for this… a fascinating read and well explained.