简体   繁体   English

在 JavaScript 中将负数转换为正数

[英]Convert a negative number to a positive one in JavaScript

JavaScript 中是否有将数字转换为正值的数学函数?

You could use this...你可以用这个...

Math.abs(x)

Math​.abs() | Math​.abs() | MDN MDN

What about x *= -1 ? x *= -1呢? I like its simplicity.我喜欢它的简单。

Math.abs(x)或者如果您确定该值在转换前为负,只需在前面加上一个常规减号: 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) . x=-yx=(y*-1)视觉糖。

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

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
unsigned_value = Math.abs(signed_value);
var posNum = (num < 0) ? num * -1 : num; // if num is negative multiple by negative one ... 

我发现这个解决方案很容易理解。

If you'd like to write interesting code that nobody else can ever update, try this:如果您想编写其他人无法更新的有趣代码,请尝试以下操作:

~--x ~--x

Multiplying by (-1) is the fastest way to convert negative number to positive.乘以 (-1) 是将负数转换为正数的最快方法。 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.然后 Math.abs、Math.floor 和 parseInt 是最慢的。

在此处输入图片说明

https://jsperf.com/test-parseint-and-math-floor-and-mathabs/1 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.它检查数字是否为负数,如果是负数,则乘以 -1 这确实返回一个值,如果您捕获它,则由您决定。 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.如果我们正常按位反转它,我们会得到一个太小的值 1。 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.这将执行相同的操作,但会先取反,然后将正数加 1。 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.这将不起作用,因为优先级,诸如num++后缀运算符将在 ~ 之前进行评估,并且即使它与按位 NOT(~) 具有相同的优先级,原因前缀++num不起作用,因为它是从右到离开了。 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. +1 将起作用,因为 '+' 具有更高的优先级,将在稍后进行评估。

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

You can use ~ operator that logically converts the number to negative and adds 1 to the negative:您可以使用~运算符将数字逻辑转换为负数并将 1 添加到负数:

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

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.这样做的问题是您可能将数字更改为负数,然后转换为字符串并从字符串中删除- ,然后转换回 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.我已经在 php 中测试过,第一个函数更快,但有时 JS 会做一些疯狂的事情,所以我不能肯定地说。

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.对于函数式编程,Ramda 有一个很好的方法。 The same method works going from positive to negative and vice versa.同样的方法从正面到负面,反之亦然。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM