Convert a negative number to a positive one in JavaScript - javascript

Is there a math function in JavaScript that converts numbers to positive value?

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.
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

Related

How to truncate extra zeros from floating point number

Say:
var x = 6.450000000000003;
var y = 5.234500000000002;
These are the results of floating point division, so the 3 and the 2 need to be removed. How can I trim x to 6.45 and y to 5.2345 given that they have different levels of precision?
You could use Number#toFixed and convert the string back to number.
var x = 6.450000000000003,
y = 5.234500000000002;
x = +x.toFixed(5);
y = +y.toFixed(5);
console.log(x);
console.log(y);
You could use Math.round but you must choose a precision.
(Otherwise, you are losing percision and you don't want that!)
var x = 6.450000000000003;
var y = 5.234500000000002;
console.log(Math.round(x * 1000000) / 1000000);
console.log(Math.round(y * 1000000) / 1000000);
Try this function. If, as you say, you're simply looking to remove the end digit and remove trailing zeros, the following code could help.
function stripZeroes(x){
// remove the last digit, that you know isn't relevant to what
// you are working on
x = x.toString().substring(0,x.toString().length-1);
// parse the (now) String back to a float. This has the added
// effect of removing trailing zeroes.
return parseFloat(x);}
// set up vars for testing the above function
var x = 6.450000000000003;
var y = 5.234500000000002;
// test function and show output
console.log(stripZeroes(x));
console.log(stripZeroes(y));

Javascript return a NaN value after a math operation

Ok, I'm not a coder, I've no school about it but ... I can't figure out why this little operation returns a NaN value!
I've this var at the beginning
// Varialbes for simulation purpose
var Simulation = false;
var FakeCapital = 0;
var PercentOfTotal = 100;
// Variables
var Capital = (engine.getBalance() / 100).toFixed(2);
var UsableBalance = Math.floor(PercentOfTotal / 100 * Capital);
var StartingBalance = UsableBalance;
if (FakeCapital > 0 && Simulation) {
Capital = FakeCapital;
UsableBalance = Math.floor(PercentOfTotal / 100 * Capital);
StartingBalance = UsableBalance;
}
So If I activate the similation var and if I want to use another capital, the script use the fakecapital to test my script.
Here all works but I think that here there's the problem, specially the UsableBalance = Math.floor(PercentOfTotal / 100 * Capital);
Because when the script run:
If I don't use the simulation, all goes right
If I use the simulation and the fake capital, all goes right
But if I use the simulation and I want to use the real capital, the UsableBalance var is strange, not immediately but when the script runs! I try to explain better
Let's assume that I use the simulation phase and I want to use the real capital
Your ballance is: 87.26 bits.
I'll use: 87 bits for this session, as your request.
Here all ok, but this code:
if (TemporaryLoss <= 0) {
Capital += LastProfit;
UsableBalance = Math.floor((PercentOfTotal / 100) * Capital);
TemporaryLoss = 0;
}
Return this:
TemporaryLoss: 0
Capital: 87.26
LastProfit: 1.0299999999999998
PercentOfTotal: 100
Capital: 87.261.0299999999999998
Why the math return this strange number? like a concatenation of 2 numbers? Seems that the script use the var like a text and not like a numbers.
Any Idea?
You make a string with toFixed()
var Capital = (engine.getBalance() / 100).toFixed(2);
and used it later as number, but it is a string.
Capital += LastProfit;
Solution: If fixed is necessary, then use parseFloat() to make a number again.
Lets take an example :
var x = 1;
var y = '1';
var z = x + (y*10)
the datatype of variable y is implicitly coerced to number for the current operation, to evaluate the value of z.
So, for z , y is taken as a number because (y*10) caused implicit coercion, but doesn't change y itself to number
In your case ,
var Capital = (engine.getBalance() / 100).toFixed(2);
causes Capital to become a string.
Hence any further addition operations with Capital result in concatenation
You will have to explicitly convert to int or float as mentioned earlier.

ES6 +new Javascript Syntax [duplicate]

I'm trying to understand unary operators in javascript, I found this guide here http://wiki.answers.com/Q/What_are_unary_operators_in_javascript most of it makes sense but what I don't understand is how the following examples would be used in an actual code example:
+a;
-a;
To my understanding the +a; is meant to make the variable the positive value of a and the -a; is meant to make the variable the negative value of a. I've tried a number of examples like:
a = -10;
a = +a;
document.writeln(a);
And the output is still -10;
I've also tried:
a = false;
a = +a;
document.writeln(a);
And the output is 0;
What is a practical code example of these unary operators?
The + operator doesn't change the sign of the value, and the - operator does change the sign. The outcome of both operators depend on the sign of the original value, neither operator makes the value positive or negative regardless of the original sign.
var a = 4;
a = -a; // -4
a = +a; // -4
The abs function does what you think that the + opreator does; it makes the value positive regardless of the original sign.
var a =-4;
a = Math.abs(a); // 4
Doing +a is practically the same as doing a * 1; it converts the value in a to a number if needed, but after that it doesn't change the value.
var a = "5";
a = +a; // 5
The + operator is used sometimes to convert string to numbers, but you have the parseInt and parseFloat functions for doing the conversion in a more specific way.
var a = "5";
a = parseInt(a, 10); //5
One example is that they can be used to convert a string to a number,
var threeStr = '3.0'
var three = +threeStr
console.log(threeStr + 3) // '3.03'
console.log(three + 3) //6
I would like to explain this from basic mathematical point:
The multiplying rules:
Positive x Positive = Positive: 3 x 2 = 6
Negative x Negative = Positive: (-2) x (-8) = 16
Negative x Positive = Negative: (-3) x 4 = -12
Positive x Negative = Negative: 3 x (-4) = -12
Considering you example:
a = -10;
a = +a
document.writeln(a);
+a = +(-10) = Positive x Negative = Negative = -10
a = false;
a = +a;
document.writeln(a);
false == 0, +a = +(+0) = Positive * Positive = Positive = 0 (maybe use true is a better example)
a = 1
b = -a
console.log(b)
output
-1
'+' operator in a variable 'a' simply means : a
'-' operator in a variable 'a' simply means : -a
Since, in above example
a=-10;
a= +a; // means a, ie, +(-10) which is -10
but,
a= -a; // means -a, ie, -(-10) which is +10
+a means a*1
and
-a means a*(-1)
Thats it!!!!!!
Try this
false == 0 // returns true
So,
a = false
a = +a //a * 1
console.log(a) // prints 0 as expected

How can I fix these calculations?

I'm taking a number, dividing by 100 and then multiplying it by 100 to have it return to it's original value. Some returned values are a little off however.
var num = 57,
num = num / 100,
// this should return the number to the original
// however in this example it returns 56.99999999999999
num = num * 100;
Here's a fiddle: http://jsfiddle.net/njsdW/
In truth, all I want to do is add two 0's in front of the number, but I'm not always sure where the decimal would be.
EDIT: My solution:
var num = 57,
num = (parseFloat((num / 100).toPrecision(15)));
// this should return the number to the original
num = (parseFloat((num * 100).toPrecision(15)));
You must save the precision of your number and restore it after dividing by 100
prec = num.length;
// adjust for decimal point
if (num.indexOf('.') != -1)
prec--;
// adjust for leading zero
if (num < 1)
prec--;
num /= 100;
self.find('h2').append(num.toPrecision(prec));
JSFiddle
You can use a JavaScript bignum implementation like javascript-bignum or gmp.js to get arbitrary precision. If you want to use gmp.js, you'd have to rewrite your application in C/C++ or write gmp.js bindings for JavaScript. In return, you'd get the battle-tested reliability and optimal algorithmic effenciency from GNU GMP.

How to perform an integer division, and separately get the remainder, in JavaScript?

In JavaScript, how do I get:
The whole number of times a given integer goes into another?
The remainder?
For some number y and some divisor x compute the quotient (quotient)[1] and remainder (remainder) as:
const quotient = Math.floor(y/x);
const remainder = y % x;
Example:
const quotient = Math.floor(13/3); // => 4 => the times 3 fits into 13
const remainder = 13 % 3; // => 1
[1] The integer number resulting from the division of one number by another
I'm no expert in bitwise operators, but here's another way to get the whole number:
var num = ~~(a / b);
This will work properly for negative numbers as well, while Math.floor() will round in the wrong direction.
This seems correct as well:
var num = (a / b) >> 0;
I did some speed tests on Firefox.
-100/3 // -33.33..., 0.3663 millisec
Math.floor(-100/3) // -34, 0.5016 millisec
~~(-100/3) // -33, 0.3619 millisec
(-100/3>>0) // -33, 0.3632 millisec
(-100/3|0) // -33, 0.3856 millisec
(-100-(-100%3))/3 // -33, 0.3591 millisec
/* a=-100, b=3 */
a/b // -33.33..., 0.4863 millisec
Math.floor(a/b) // -34, 0.6019 millisec
~~(a/b) // -33, 0.5148 millisec
(a/b>>0) // -33, 0.5048 millisec
(a/b|0) // -33, 0.5078 millisec
(a-(a%b))/b // -33, 0.6649 millisec
The above is based on 10 million trials for each.
Conclusion: Use (a/b>>0) (or (~~(a/b)) or (a/b|0)) to achieve about 20% gain in efficiency. Also keep in mind that they are all inconsistent with Math.floor, when a/b<0 && a%b!=0.
ES6 introduces the new Math.trunc method. This allows to fix #MarkElliot's answer to make it work for negative numbers too:
var div = Math.trunc(y/x);
var rem = y % x;
Note that Math methods have the advantage over bitwise operators that they work with numbers over 231.
I normally use:
const quotient = (a - a % b) / b;
const remainder = a % b;
It's probably not the most elegant, but it works.
var remainder = x % y;
return (x - remainder) / y;
You can use the function parseInt to get a truncated result.
parseInt(a/b)
To get a remainder, use mod operator:
a%b
parseInt have some pitfalls with strings, to avoid use radix parameter with base 10
parseInt("09", 10)
In some cases the string representation of the number can be a scientific notation, in this case, parseInt will produce a wrong result.
parseInt(100000000000000000000000000000000, 10) // 1e+32
This call will produce 1 as result.
Math.floor(operation) returns the rounded down value of the operation.
Example of 1st question:
const x = 5;
const y = 10.4;
const z = Math.floor(x + y);
console.log(z);
Example of 2nd question:
const x = 14;
const y = 5;
const z = Math.floor(x % y);
console.log(x);
JavaScript calculates right the floor of negative numbers and the remainder of non-integer numbers, following the mathematical definitions for them.
FLOOR is defined as "the largest integer number smaller than the parameter", thus:
positive numbers: FLOOR(X)=integer part of X;
negative numbers: FLOOR(X)=integer part of X minus 1 (because it must be SMALLER than the parameter, i.e., more negative!)
REMAINDER is defined as the "left over" of a division (Euclidean arithmetic). When the dividend is not an integer, the quotient is usually also not an integer, i.e., there is no remainder, but if the quotient is forced to be an integer (and that's what happens when someone tries to get the remainder or modulus of a floating-point number), there will be a non-integer "left over", obviously.
JavaScript does calculate everything as expected, so the programmer must be careful to ask the proper questions (and people should be careful to answer what is asked!) Yarin's first question was NOT "what is the integer division of X by Y", but, instead, "the WHOLE number of times a given integer GOES INTO another". For positive numbers, the answer is the same for both, but not for negative numbers, because the integer division (dividend by divisor) will be -1 smaller than the times a number (divisor) "goes into" another (dividend). In other words, FLOOR will return the correct answer for an integer division of a negative number, but Yarin didn't ask that!
gammax answered correctly, that code works as asked by Yarin. On the other hand, Samuel is wrong, he didn't do the maths, I guess, or he would have seen that it does work (also, he didn't say what was the divisor of his example, but I hope it was 3):
Remainder = X % Y = -100 % 3 = -1
GoesInto = (X - Remainder) / Y = (-100 - -1) / 3 = -99 / 3 = -33
By the way, I tested the code on Firefox 27.0.1, it worked as expected, with positive and negative numbers and also with non-integer values, both for dividend and divisor. Example:
-100.34 / 3.57: GoesInto = -28, Remainder = -0.3800000000000079
Yes, I noticed, there is a precision problem there, but I didn't had time to check it (I don't know if it's a problem with Firefox, Windows 7 or with my CPU's FPU). For Yarin's question, though, which only involves integers, the gammax's code works perfectly.
const idivmod = (a, b) => [a/b |0, a%b];
there is also a proposal working on it
Modulus and Additional Integer Math
Alex Moore-Niemi's comment as an answer:
For Rubyists here from Google in search of divmod, you can implement it as such:
function divmod(x, y) {
var div = Math.trunc(x/y);
var rem = x % y;
return [div, rem];
}
Result:
// [2, 33]
If you need to calculate the remainder for very large integers, which the JS runtime cannot represent as such (any integer greater than 2^32 is represented as a float and so it loses precision), you need to do some trick.
This is especially important for checking many case of check digits which are present in many instances of our daily life (bank account numbers, credit cards, ...)
First of all you need your number as a string (otherwise you have already lost precision and the remainder does not make sense).
str = '123456789123456789123456789'
You now need to split your string in smaller parts, small enough so the concatenation of any remainder and a piece of string can fit in 9 digits.
digits = 9 - String(divisor).length
Prepare a regular expression to split the string
splitter = new RegExp(`.{1,${digits}}(?=(.{${digits}})+$)`, 'g')
For instance, if digits is 7, the regexp is
/.{1,7}(?=(.{7})+$)/g
It matches a nonempty substring of maximum length 7, which is followed ((?=...) is a positive lookahead) by a number of characters that is multiple of 7. The 'g' is to make the expression run through all string, not stopping at first match.
Now convert each part to integer, and calculate the remainders by reduce (adding back the previous remainder - or 0 - multiplied by the correct power of 10):
reducer = (rem, piece) => (rem * Math.pow(10, digits) + piece) % divisor
This will work because of the "subtraction" remainder algorithm:
n mod d = (n - kd) mod d
which allows to replace any 'initial part' of the decimal representation of a number with its remainder, without affecting the final remainder.
The final code would look like:
function remainder(num, div) {
const digits = 9 - String(div).length;
const splitter = new RegExp(`.{1,${digits}}(?=(.{${digits}})+$)`, 'g');
const mult = Math.pow(10, digits);
const reducer = (rem, piece) => (rem * mult + piece) % div;
return str.match(splitter).map(Number).reduce(reducer, 0);
}
If you are just dividing with powers of two, you can use bitwise operators:
export function divideBy2(num) {
return [num >> 1, num & 1];
}
export function divideBy4(num) {
return [num >> 2, num & 3];
}
export function divideBy8(num) {
return [num >> 3, num & 7];
}
(The first is the quotient, the second the remainder)
function integerDivison(dividend, divisor){
this.Division = dividend/divisor;
this.Quotient = Math.floor(dividend/divisor);
this.Remainder = dividend%divisor;
this.calculate = ()=>{
return {Value:this.Division,Quotient:this.Quotient,Remainder:this.Remainder};
}
}
var divide = new integerDivison(5,2);
console.log(divide.Quotient) //to get Quotient of two value
console.log(divide.division) //to get Floating division of two value
console.log(divide.Remainder) //to get Remainder of two value
console.log(divide.calculate()) //to get object containing all the values
You can use ternary to decide how to handle positive and negative integer values as well.
var myInt = (y > 0) ? Math.floor(y/x) : Math.floor(y/x) + 1
If the number is a positive, all is fine. If the number is a negative, it will add 1 because of how Math.floor handles negatives.
This will always truncate towards zero.
Not sure if it is too late, but here it goes:
function intdiv(dividend, divisor) {
divisor = divisor - divisor % 1;
if (divisor == 0) throw new Error("division by zero");
dividend = dividend - dividend % 1;
var rem = dividend % divisor;
return {
remainder: rem,
quotient: (dividend - rem) / divisor
};
}
Calculating number of pages may be done in one step:
Math.ceil(x/y)
Here is a way to do this. (Personally I would not do it this way, but thought it was a fun way to do it for an example) The ways mentioned above are definitely better as this calls multiple functions and is therefore slower as well as takes up more room in your bundle.
function intDivide(numerator, denominator) {
return parseInt((numerator/denominator).toString().split(".")[0]);
}
let x = intDivide(4,5);
let y = intDivide(5,5);
let z = intDivide(6,5);
console.log(x);
console.log(y);
console.log(z);

Categories

Resources