JavaScript typecasting issue while addition - javascript

When I use prompt() method in JavaScript as follows:
var n=prompt("Enter an integer"); //passing 2 as value
n=(n+n);
document.writeln("n+n value is:"+n);
Then (n+n) gets concatenated as 22 instead of addition as 4
But when I don't use prompt() ie.:
var n=2;
n=(n+n)
document.writeln("n+n value is:"+n);
then it works fine for addition and answer is 4
Why is it so?

prompt("Enter an integer"); returns string
convert it after, you can use parseInt()
var n = parseInt(prompt("Enter an integer"));
SEE FIDDLE DEMO

Use parseInt to convert String to Int
var n = parseInt( prompt("Enter an integer") ); //passing 2 as value
n=(n+n);
document.writeln("n+n value is:"+n);
More info here

A variable declared with datatype var can hold any type of variable which is assigned to it at a moment of time.
eg.
var j = 1; // here j will be an integer datatype and will act as int after this
var j = "1"; //here j will be a string datatype and will act as int after this
in your first case
var n=prompt("Enter an integer");
here a string will be saved in variable 'n'. hence n will act as a string variable. Therefore (n+n) will result in concatenation of two strings.
In your second case
var n = 2;
In here n is holding an integer therefore n acts as int variable.
Thats why (n+n) results into a SUM instead of concatenation.

Change
var n =prompt("Enter an integer")
to
var n = Number( prompt("Enter an integer") )
As if you do console.log(typeof n) you will get a string which means n is actually a string.
So concatenation of
n = '2' + '2';
is '22'
Hence you need to change it to a number. For this you can use Number() or parseInt().

Related

From string to integer Javascript

function FinalAmount() {
var FinalPrice = document.getElementById("FinalPrice");
let AllProductTotalPrice = 0;
for (let index = 0; index < OrderedProductList.length; ++index) {
alert;
var CurrentProductTotal = 0;
CurrentProductTotal = OrderedProductList[index].TotalPrice;
console.log(CurrentProductTotal);
AllProductTotalPrice += CurrentProductTotal;
console.log(AllProductTotalPrice);
}
FinalAllProductPrice = AllProductTotalPrice;
FinalPrice.innerText = "RM" + FinalAllProductPrice;
}
This is my javascript code. I would have a question about why the console.log(CurrentProductTotal) is already an integer but the above AllProductTotalPrice is a string value. Is there any way to let its sum as an integer and bring it to the below FinalAllProductPrice. Please help me TT
I think the easiest way would be to
use Number() to parse a string to a number. (we don't define integers specifically in javascript)
const num = "1234"
Number(num)
⚠️ If you give it a string which does not solely consist out of numbers it will return NaN
So in your example that would be:
CurrentProductTotal = OrderedProductList[index].TotalPrice
Now to your questions:
console.log() automatically displays it formatted for you. I would use the typeof operator to check whether CurrentProductTotal is really a number, or a string which the console formats differently which is a bit confusing.
Try this in your browser console:
const num = "1234"
> undefined
num
> '1234'
console.log(num)
> 1234 // formatted like a number
console.log(num, typeof num)
> 1234 string // still formatted like a number, but a string in reality

How to convert string to number and keep string if it's not a number in javascript?

I tried several methods (Number, parseFloat, *1) of string to number conversion but everytime I can't get desired value:
var str = ["0.20", "day"];
var num;
str.forEach(v => {
num = parseFloat(v);
console.log(num);
})
How can I get 0.2 as a number and "day" as a string [0.2, "day"] in the result?
Check if the parsed value is not a number (NaN). If so, print the string as it is, otherwise convert it.
l = parseFloat(v) Here I try to convert the value to float and assign the result to the variable l
isNaN() Is the built in method that checks if a certain result is not a number and is what I use to check if variable l is a number or not.
? is a ternary operator
v is printed if it is not a number (if it is NaN)
Otherwise l (which is the parsed value) is printed
var str = ["0.20", "day"];
console.log(
str.map(v => isNaN(l = parseFloat(v))? v : l)
)
/* A shorter way is to do */
console.log(
str.map(v=>+v||v)
)

Parse String to Integer

I have a string variable, for example:
var value = "109.90"
I need to pass this variable as an integer to webservice in this format: 10990
I tried parsing it to integer with parseInt(value) but I got 109
And with parseFloat(value) I got 109.9
Any help would be appreciated!
Same as in the other answers, but more readable code.
var value = "109.90";
// Replace the decimal point with an empty string
var valueWithoutDecimalPoint = String(value).replace(".", "");
// Parse an integer with the radix value
// This will tell parseInt to use 10-based decimal numbers
// Otherwise you will get weird bugs if your string starts with a 0
var result = parseInt(valueWithoutDecimalPoint, 10);
// It will be NaN if int cannot be parsed
isNaN(result) ? console.error("result is NaN!") : console.log(result); // 10990
Something like this?
var value = "109.90";
let result = parseInt(`${value.split(".")[0]}${value.split(".")[1]}`);
console.log(result);
Ok, this is probably nicer than my other answer:
var result = value * 100

Confusion with arithmetic operators in Javascript

While I do know that the following question is stupid simple, it is related to a specific situation that I have been unable to find through Google. The following code is in Javascript.
Suppose there is a variable
x = x + 1;
I can see from a tutorial that this is supposed to work. However, how are we supposed to use this variable in a calculation?
I have tried with the following codes
var name = name + 1;
alert(name);
The above outputs "NaN"; whatever that is...
var name = name + 1;
name = 2;
alert(name);
The above outputs 2 which is simply overriding the original variable.
name = prompt("input any number");
var name = name + 1
alert(name);
The above outputs the input provided + 1 as a string, i.e. 01 where the input is "0" without quotes.
I remember from a ruby lesson that we use .to_i in order to convert a string to an integer. How do we go about doing this in Javascript?
var name = name + 1;
The above code declares a new variable called name which contains whatever name contained before, plus 1. Since name only just came into existence, it doesn't have a numeric value ("Not A Number", or NaN). Adding 1 to NaN gives NaN.
+ means different things in different contexts. If the two operands are numbers, then it does addition. If one operand is a String, it does String concatenation, so
var x = "2"; // x is the String "2"
alert(x+2); // "22"
var x = 2; // x is the number 2
alert(x+2); // 4
If you want to convert a String to a number, you can do
if (x) x = parseInt(x, 10);
where the second argument is the radix (i.e. the base of the number system), and you should use it. If someone entered 02 for example, the radix prevents javascript from treating that as an octal (or other) number.
Of course, you always need to make sure your variables are defined before you use them. I bet your NaN result is coming from the variable not being defined.
Your issue is that you never initialize name. For example:
var name = 0;
alert(name); // Name is 0
name = name + 1;
alert(name); // Name is 1
If you don't initialize it, it will give you NaN: Not a Number.
To turn a string into a number, use parseInt or parseFloat:
var name = prompt("input any number"); // I input 3
name = parseFloat(name);
name = name + 1;
alert(name); // Name is 4
Use parseInt to convert a string to a number.
The line x = x + 1 says "take the existing value of x, add one to it, and store the resulting value back in x again".
The line var name = name + 1 is meaningless since name does not have an existing value when the statement is executed. It is the same as saying undefined + 1 which is NaN (Not a Number).
Here are some examples of how the + operator works in JavaScript:
1 + 2 // number + number is a number -> 3
"1" + 2 // string + anything is a string => "12"
1 + "2" // anything + string is a string => "12"
"1" + "2" // string + string is a string => "12"
NaN means "not a number". Since name has no value when it is first declared, saying "var name = name + 1" doesn't have a numerical meaning, since name is in the process of being declared when used for the first time.
In the second example, name is determined to be a string. Javascript isn't as sensitive to types as some other languages, so it uses + as a concatenation operator instead of a numerical one, since it makes more sense in context,

how to read value zero using parseInt function

var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
var resstr=result.toString();
var res=resstr.split(".");
var test=parseInt(res[1].charAt(0));
var test1=parseInt(res[1].charAt(1));
this is my code when my value in res variable is 5.90 then I alert test & test1 variable
in test alert it shows correct value i.e. "9" but in test1 alert it shows message like "Nan"
if res variable contain value 5.35 then it work correct i.e.test=3 & test1=5
only it does not work when test1 contains value "0" it gives message "Nan"
The problem is that you create a string such as '12.3', and split it to 3. .charAt(1) on that string returns an empty string, '', which parseInt turns into a NaN.
Well, an easy and hacky fix would be:
test1 = test1 || 0;
You may also consider a calculation instead of string manipulation:
var result = 98.1234;
var d1 = Math.floor(result * 10) % 10;
var d2 = Math.floor(result * 100) % 10;

Categories