what's the differences between (variable).toFixed(2) and +(variable).toFixed(2)? - javascript

I'm wondering what's the main differences between
(2.3444).toFixed(2) ==> 2.34
Also
+(2.3444).toFixed(2) ==> 2.34
Both of them giving the same results. Can any one explain when I need to use that + sign?

The first gives you a string, the second gives you a (now truncated) number.
var x = 2.344;
var a = x.toFixed(2);
var b = +x.toFixed(2);
console.log(a, typeof a);
console.log(b, typeof b);
A unary plus will attempt to convert it's operand to a number.
The reason this matters is because the first one will lead to string concatenation if you "add" a number to it.
var x = 2.344;
var strNumber = x.toFixed(2);
console.log(strNumber);
console.log(strNumber + 5); // Expected: 7.34, actual: 2.345

Related

How do I allow decimal input with the correct javascript? [duplicate]

Any number, it's number. String looks like a number, it's number. Everything else, it goes NaN.
'a' => NaN
'1' => 1
1 => 1
There are 4 ways to do it as far as I know.
Number(x);
parseInt(x, 10);
parseFloat(x);
+x;
By this quick test I made, it actually depends on browsers.
https://jsben.ch/NnBKM
Implicit marked the fastest on 3 browsers, but it makes the code hard to read… So choose whatever you feel like it!
There are at least 5 ways to do this:
If you want to convert to integers only, another fast (and short) way is the double-bitwise not (i.e. using two tilde characters):
e.g.
~~x;
Reference: http://james.padolsey.com/cool-stuff/double-bitwise-not/
The 5 common ways I know so far to convert a string to a number all have their differences (there are more bitwise operators that work, but they all give the same result as ~~). This JSFiddle shows the different results you can expect in the debug console: http://jsfiddle.net/TrueBlueAussie/j7x0q0e3/22/
var values = ["123",
undefined,
"not a number",
"123.45",
"1234 error",
"2147483648",
"4999999999"
];
for (var i = 0; i < values.length; i++){
var x = values[i];
console.log(x);
console.log(" Number(x) = " + Number(x));
console.log(" parseInt(x, 10) = " + parseInt(x, 10));
console.log(" parseFloat(x) = " + parseFloat(x));
console.log(" +x = " + +x);
console.log(" ~~x = " + ~~x);
}
Debug console:
123
Number(x) = 123
parseInt(x, 10) = 123
parseFloat(x) = 123
+x = 123
~~x = 123
undefined
Number(x) = NaN
parseInt(x, 10) = NaN
parseFloat(x) = NaN
+x = NaN
~~x = 0
null
Number(x) = 0
parseInt(x, 10) = NaN
parseFloat(x) = NaN
+x = 0
~~x = 0
"not a number"
Number(x) = NaN
parseInt(x, 10) = NaN
parseFloat(x) = NaN
+x = NaN
~~x = 0
123.45
Number(x) = 123.45
parseInt(x, 10) = 123
parseFloat(x) = 123.45
+x = 123.45
~~x = 123
1234 error
Number(x) = NaN
parseInt(x, 10) = 1234
parseFloat(x) = 1234
+x = NaN
~~x = 0
2147483648
Number(x) = 2147483648
parseInt(x, 10) = 2147483648
parseFloat(x) = 2147483648
+x = 2147483648
~~x = -2147483648
4999999999
Number(x) = 4999999999
parseInt(x, 10) = 4999999999
parseFloat(x) = 4999999999
+x = 4999999999
~~x = 705032703
The ~~x version results in a number in "more" cases, where others often result in undefined, but it fails for invalid input (e.g. it will return 0 if the string contains non-number characters after a valid number).
Overflow
Please note: Integer overflow and/or bit truncation can occur with ~~, but not the other conversions. While it is unusual to be entering such large values, you need to be aware of this. Example updated to include much larger values.
Some Perf tests indicate that the standard parseInt and parseFloat functions are actually the fastest options, presumably highly optimised by browsers, but it all depends on your requirement as all options are fast enough: http://jsperf.com/best-of-string-to-number-conversion/37
This all depends on how the perf tests are configured as some show parseInt/parseFloat to be much slower.
My theory is:
Lies
Darn lines
Statistics
JSPerf results :)
Prefix the string with the + operator.
console.log(+'a') // NaN
console.log(+'1') // 1
console.log(+1) // 1
A fast way to convert strings to an integer is to use a bitwise or, like so:
x | 0
While it depends on how it is implemented, in theory it should be relatively fast (at least as fast as +x) since it will first cast x to a number and then perform a very efficient or.
Here is simple way to do it: var num = Number(str); in this example str is the variable that contains the string.
You can tested and see how it works open: Google chrome developer tools, then go to the console and paste the following code.
read the comments to understand better how the conversion is done.
// Here Im creating my variable as a string
var str = "258";
// here im printing the string variable: str
console.log ( str );
// here Im using typeof , this tells me that the variable str is the type: string
console.log ("The variable str is type: " + typeof str);
// here is where the conversion happens
// Number will take the string in the parentesis and transform it to a variable num as type: number
var num = Number(str);
console.log ("The variable num is type: " + typeof num);
I find that num * 1 is simple, clear, and works for integers and floats...
This is probably not that fast, but has the added benefit of making sure your number is at least a certain value (e.g. 0), or at most a certain value:
Math.max(input, 0);
If you need to ensure a minimum value, usually you'd do
var number = Number(input);
if (number < 0) number = 0;
Math.max(..., 0) saves you from writing two statements.
7 ways to convert a String to Number:
let str = "43.2"
1. Number(str) => 43.2
2. parseInt(str) => 43
3. parseFloat(str) => 43.2
4. +str => 43
5. str * 1 => 43.2
6. Math.floor(str) => 43
7. ~~str => 43
You can try using UnitOf, a measurement and data type conversion library we just officially released! UnitOf is super fast, small in size, and efficient at converting any data type without ever throwing an error or null/undefined. Default values you define or UnitOf's defaults are returned when a conversion is unsuccessful.
//One liner examples
UnitOf.DataType("12.5").toFloat(); //12.5 of type Float is returned. 0 would be returned if conversion failed.
UnitOf.DataType("Not A Num").toInt(10); //10 of type Int is returned as the conversion failed.
//Or as a variable
var unit = UnitOf.DataType("12.5");
unit.toInt(5); //12.5 of type Float is returned. 5 would be returned if the conversion failed.
unit.toFloat(8); // 12 of type Int is returned. 8 would be returned if the conversion failed.
The fastest way is using -0:
const num = "12.34" - 0;

Javascript Arithmetics

When we subtract/multiply/divide a number with a number(type as string), it will treat both variable as number.
But when we add a number with a number(type as string), it will treat second var as string and concat the variables.
For example
var a = 4;
var b = "4";
var c;
c = a + b;
console.log(c)
c = a - b;
console.log(c)
c = a * b;
console.log(c)
c = a / b;
console.log(c)
Result output is
"44"
0
16
1
Why there is different behaviour for addition in javascript?
Because "+" ist not only an arithmetic operator but also the "string concatination operator".
In your first example you concatenate 2 strings.
In your other examples the string is coerced to a number and then the arithmetic operation is executed.
There are some steps to prevent this from happening:
var a = 4;
var b = "4";
c = +b + a // 8
console.log(c);
c = parseInt(b) + a // 8
console.log(c);
c = b*1 + a // 8
console.log(c);
You just have to make sure that both variables have the type number when you add them together.
This is because + operator is also used for string concatenation. You can use the + operator incase you want to convert in into a number
var a = 4;
var b = "4";
console.log(a + b);
console.log(a + +b);
In JavaScript + operates both as ADD and string concatination. When you do a + b, a is implicitly coerced into a string. Whereas with other operators cannot be used on strings. Therefore a is implicitly coerced into number, so the math operation.

Explain +var and -var unary operator in javascript

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

Difference between += and =+ in javascript

I want to know why after running the third line of code the result of a is 5?
a = 10;
b = 5;
a =+ b;
Awkward formatting:
a =+ b;
is equivalent to:
a = +b;
And +b is just a fancy way of casting b to number, like here:
var str = "123";
var num = +str;
You probably wanted:
a += b;
being equivalent to:
a = a + b;
The + sign before the function, actually called Unary plus and is part of a group called a Unary Operators and (the Unary Plus) is used to convert string and other representations to numbers (integers or floats).
A unary operation is an operation with only one operand, i.e. a single input. This is in contrast to binary operations, which use two operands.
Basic Uses:
const x = "1";
const y = "-1";
const n = "7.77";
console.log(+x);
// expected output: 1
console.log(+n);
// expected output: 7.77
console.log(+y);
// expected output: -1
console.log(+'');
// expected output: 0
console.log(+true);
// expected output: 1
console.log(+false);
// expected output: 0
console.log(+'hello');
// expected output: NaN
When the + sign is positioned before a variable, function or any returned string representations the output will be converted to integer or float; the unary operator (+) converts as well the non-string values true, false, and null.

how to prevent chain when adding javascript variables containing numbers

How can i prevent to javascript interpret my numeric vars from string vars?
var a = 100;
var b = -10
var c = a + b // 10-10 (string)
lets say i allways want
var c = a + b = 100+(-10) = 90 (number)
In your example c will always be 90, however;
var a = 100;
var b = "-10";
var c = a + b // "100-10" (string)
to prevent this convert the string to an integer;
var c = a + parseInt(b, 10);
or with a unary+
var c = a + +b;
Your code example...
var a = 100;
var b = -10
var c = a + b // 90 (number)
...won't do that unless one of the operands is a String. In your example, both are Number.
If you do have numbers inside of Strings, you can use parseInt() (don't forget to pass the radix of 10 if working in decimal) or possibly just prefix the String with + to coerce it to Number.
Your code works fine. See here.
JavaScript will always do the latter, as long as both of the variables you are adding are numbers.
The most concise way is prepending a + if you aren't certain whether the variables are numbers or strings:
var a = "100";
var b = "-10";
var c = +a + +b; // 90
This works since +"123" === 123 etc.

Categories