With this function:
function test(){
toReturn = 90;
reference = 0;
// haz cosas para lograr que reference sea igual a 90
}
After the function I want to do a conditional as simple as
if (toReturn !== reference){
haz x
}
To filter when the function test()
fails to put the same value to reference
as the one it hastoReturn
The problem is that my function is somewhat sloppy and it never manages to put exactly the value of toReturn
but instead puts something like 90.00005...etc But this doesn't matter to me, it works for me. But then if I put toReturn !== reference
the conditional will always be fulfilled.
I want it to be true only when there is a difference of at least 1 or more (and not 0.1 for example) between toReturn
and reference
. How do I do that?
if (hay una diferencia de al menos 1 entre toReturn y reference){
haz x
}
To see the difference between two integers, the simplest operation is division.
That is, a/b will tell you how many times a is greater than b, but it will give you decimals.
you can always do
a/b > 1
That being said, if what you want is an integer result from decimals or you just want to keep the integer part of the integer you can do
Math.floor(x)
I leave you a snippet with different options that you have:
In this way you could do any of these options:
toReturn/reference >= 1
isTimesBigger(toReturn, reference, 1)
isEntirePartTimesBigger(toReturn, reference, 1)
In the end, the last two options are an encapsulator of the first, I recommend you only use the first, which is the most direct and the decimals will count for the evaluation.
In any case, this only works for 90.00001 and not for 89.999999 which, as has been commented in other answers, you can also round off with respect to an order instead of
Math.floor()
.It is typical to lose precision when doing floating point operations. If you are only interested in the integer part, an easy solution is to round the number:
If you want to be able to choose the number of decimal places, you can do something like: