开发者

Convert a negative number to a positive one in JavaScript

开发者 https://www.devze.com 2023-02-03 18:02 出处:网络
Is there a math function in JavaScript that converts numbers to positive value开发者_Go百科?You could use this...

Is there a math function in JavaScript that converts numbers to positive value开发者_Go百科?


You could use this...

Math.abs(x)

Math​.abs() | MDN


What about x *= -1? I like its simplicity.


I know this is a bit late, but for people struggling with this, you can use the following functions:

  • Turn any number positive

    let x =  54;
    let y = -54;
    let resultx =  Math.abs(x); //  54
    let resulty =  Math.abs(y); //  54
    
  • Turn any number negative

    let x =  54;
    let y = -54;
    let resultx = -Math.abs(x); // -54
    let resulty = -Math.abs(y); // -54
    
  • Invert any number

    let x =  54;
    let y = -54;
    let resultx = -(x);         // -54
    let resulty = -(y);         //  54
    


Math.abs(x) or if you are certain the value is negative before the conversion just prepend a regular minus sign: x = -x.


The minus sign (-) can convert positive numbers to negative numbers and negative numbers to positive numbers. x=-y is visual sugar for x=(y*-1).

var y = -100;
var x =- y;


unsigned_value = Math.abs(signed_value);


var posNum = (num < 0) ? num * -1 : num; // if num is negative multiple by negative one ... 

I find this solution easy to understand.


If you'd like to write interesting code that nobody else can ever update, try this:

~--x


Multiplying by (-1) is the fastest way to convert negative number to positive. But you have to be careful not to convert my mistake a positive number to negative! So additional check is needed...

Then Math.abs, Math.floor and parseInt is the slowest.

Convert a negative number to a positive one in JavaScript

https://jsperf.com/test-parseint-and-math-floor-and-mathabs/1


Negative to positive

var X = -10 ;
var number = Math.abs(X);     //result 10

Positive to negative

var X = 10 ;
var number = (X)*(-1);       //result -10


I did something like this myself.

num<0?num*=-1:'';

It checks if the number is negative and if it is, multiply with -1 This does return a value, its up to you if you capture it. In case you want to assign it to something, you should probably do something like:

var out = num<0?num*=-1:num; //I think someone already mentioned this variant.

But it really depends what your goal is. For me it was simple, make it positive if negative, else do nothing. Hence the '' in the code. In this case i used tertiary operator cause I wanted to, it could very well be:

if(num<0)num*=-1;

I saw the bitwise solution here and wanted to comment on that one too.

~--num; //Drawback for this is that num original value will be reduced by 1

This soultion is very fancy in my opinion, we could rewrite it like this:

~(num = num-1);

In simple terms, we take the negative number, take one away from it and then bitwise invert it. If we had bitwise inverted it normally we would get a value 1 too small. You can also do this:

~num+1; //Wont change the actual num value, merely returns the new value

That will do the same but will invert first and then add 1 to the positive number. Although you CANT do this:

~num++; //Wont display the right value.

That will not work cause of precedence, postfix operators such as num++ would be evaluated before ~ and the reason prefix ++num wouldnt work even though it is on the same precedence as bitwise NOT(~), is cause it is evaluated from right to left. I did try to swap them around but it seems that prefix is a little finicky compared to bitwise NOT. The +1 will work because '+' has a higher precedence and will be evaluated later.

I found that solution to be rather fun and decided to expand on it as it was just thrown in there and post people looking at it were probably ignoring it. Although yes, it wont work with floats.

My hopes are that this post hasn't moved away from the original question. :/


My minimal approach

For converting negative number to positive & vice-versa

var num = -24;
num -= num*2;
console.log(num)
// result = 24


If you want the number to always be positive no matter what you can do this.

function toPositive(n){
    if(n < 0){
        n = n * -1;
    }
    return n;
}
var a = toPositive(2);  // 2
var b = toPositive(-2); // 2

You could also try this, but i don't recommended it:

function makePositive(n){
    return Number((n*-n).toString().replace('-','')); 
}
var a = makePositive(2);  // 2
var b = makePositive(-2); // 2

The problem with this is that you could be changing the number to negative, then converting to string and removing the - from the string, then converting back to int. Which I would guess would take more processing then just using the other function.

I have tested this in php and the first function is faster, but sometimes JS does some crazy things, so I can't say for sure.


You can use ~ operator that logically converts the number to negative and adds 1 to the negative:

var x = 3;
x = (~x + 1);
console.log(x)
// result = -3


I know another way to do it. This technique works negative to positive & Vice Versa

var x = -24;
var result = x * -1;

Vice Versa:

var x = 58;
var result = x * -1;

LIVE CODE:

// NEGATIVE TO POSITIVE: ******************************************
var x = -24;
var result = x * -1;
console.log(result);

// VICE VERSA: ****************************************************
var x = 58;
var result = x * -1;
console.log(result);

// FLOATING POINTS: ***********************************************
var x = 42.8;
var result = x * -1;
console.log(result);

// FLOATING POINTS VICE VERSA: ************************************
var x = -76.8;
var result = x * -1;
console.log(result);


For a functional programming Ramda has a nice method for this. The same method works going from positive to negative and vice versa.

https://ramdajs.com/docs/#negate

0

精彩评论

暂无评论...
验证码 换一张
取 消