I'm looking for a method that given 2 floats A and B return the value (A or B) with lower absolute value.
Initially I tried
Math.min(Math.abs(A),Math.abs(B));
but it is not correct because for example for (-9,-2) return +2 and the return value I'm looking for is -2.
Is there some native/built-in for that?
Math.abs(A) < Math.abs(B) ? A : B;
我不赞成对局部变量使用大写,但是
(Math.abs(A) < Math.abs(B)) ? A : B
Math.min()
returns the lowest of the two parameters passed into it. In the example above, you're providing it with arguments of 999
and 2
(The absolute values generated by Math.abs()
.
You could replace the Math.min()
call with something like:
Math.abs(A) < Math.abs(B) ? A : B;
val = (Math.abs(A) < Math.abs(B)) ? A : B;
Well, it's a correct behaviour.
You're getting the absolute value of both numbers inside the Min funcion which returns the minimum value of both. In your case that's 2 because you're comparing 9 and 2.
EDIT
AFAIK There's not built-in way to do what you want to do. As others have suggested, you have to make the comparation yourself with something like:
Math.abs(A) < Math.abs(B) ? A : B
Just remember to be careful with the types you compare and the result.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.