Javascript Number Increase / Decrease Accuracy

I work with values โ€‹โ€‹between 0 and 1 with 2 decimal points.

I am trying to increment from 0 to 1 in increments of 0.01, but run into problems:

In a function that calls itself recursively, the following.

if ($Y.drawChallengeTextAlpha.toFixed(1) < 1) $Y.drawChallengeTextAlpha += 0.01; 

I never get minus 0.95.

EDIT

I got the following:

 // $Y.drawChallengeTextAlpha is an integer from 0 to 100 if ($Y.drawChallengeTextAlpha < 100) $Y.drawChallengeTextAlpha += 1; // May not always be 1 

Then I get the exact value using ($ Y.drawChallengeTextAlpha / 100)

+4
source share
5 answers

toFixed rounds the number of UPs, so you start getting return values โ€‹โ€‹of 1 when you get close to 0.95.

Floating points are messy. If you really need it to be 100% accurate, use an integer variable, increment it by 1 at each iteration, check when it reaches 100, and then, for the actual calculation, take your variable and divide it by 100 to get decimal value you need.

+4
source
 (0.959).toFixed(1) 

This returns "1" in Firefox. Is there a reason you use toFixed , not just testing if the number is less than 1?

(By the way, 0.01 cannot be represented as a non-determinative sequence of binary digits, so be careful that it is not going to add up to 1 out of 100 iterations, this will require at least 101.)

0
source

Perhaps this is because typeof (3).toString() returns a string , for example. Why don't you compare it with the actual number?

0
source

why you just don't use:

 if ($Y.drawChallengeTextAlpha < 1) $Y.drawChallengeTextAlpha += 0.01; 

Without .toFixed function (1)? I think everything will be fine.

You can try:

 if (parseInt($Y.drawChallengeTextAlpha) < 1) $Y.drawChallengeTextAlpha += 0.01; 

parseInt will be rounded, so if you have float / double less than 1, it will return 0. Above 1 and less than 2, will return 1, etc.

0
source

toFixed() rounds up. .96.toFixed(1) - 1 . Go to toFixed(2) .

0
source

All Articles