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;
Related
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
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().
I have a very stupid problem. This code:
var x=5;
console.log(x*20+x-1);
prints out 104 as expected but this:
function Go(){
x = document.getElementById("input").value;
console.log(x);
console.log(x*20+x-1);
}
prints out 5 and then 1004. Why is this?
console.log(x*20) prints 100. I tried putting brackets around it and then adding (x-1) but it still outputs 1004.
The value property of the input element is a string, so your x is actually "5"—not the number 5. What follows is JavaScript’s way of doing implicit type conversion for arithmetics:
"5" * 20 + "5" - 1
= 100 + "5" - 1
= "1005" - 1
= 1004
So in the first step, "5" is correctly converted to the number 5, leaving 100 as the intermediary result. However, adding a string to a number will convert the number into a string, so what happens next is a string concatenation to "1005". Finally, the number 1 is subtracted from the string, which causes the string to be converted to a number again, yielding the final result: 1004.
To avoid this, you can simply convert the x to a number first:
var x = document.getElementById("input").value;
x = parseInt(x, 10); // or parseFloat(x) if you’re interested in a decimals
console.log(x * 20 + x - 1);
Fun fact: If you wrote x * 21 - 1, which is equivalent to your calculation, the problem wouldn’t have appeared.
The value of an input element is a string value, so what you are getting is:
"5" * 20 = 100
100 + "5" = "1005"
"1005" - 1 = 1004
This has nothing to do with being in a function or not. Your two code snippets are not equivalent.
You can solve this by doing:
function Go(){
x = +(document.getElementById("input").value);
console.log(x);
console.log(x*20+x-1);
}
That will convert the input element value to a numeric value at the beginning.
document.getElementById("input").value returns a string. You need to convert it to and integer for it to work. So use parseInt()
function Go(){
x = parseInt(document.getElementById("input").value);
console.log(x);
console.log(x*20+x-1);
}
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,
I have two variables, 'a' and 'b' in my JavaScript, and i want to add them together - i assume this code:
var a = 10;
var b = 30
var varible = a + b;
This, puts the two numbers next to each other... any ideas why... the result should be 40?
You probably have strings instead of integers. That is your code really is like this:
var a = "10";
var b = "30";
var c = a + b; // "1030"
There are several ways to convert the strings to integers:
a = parseInt(a, 10); // Parse the string
b = b * 1; // Force interpretation as number
new is a reserved word, I'd use something else in any case.
And with a normal variable name of c it worked for me:
var a = 10;
var b = 30
var c = a + b;
alert(c);
did the expected and alerted 40
new is a keyword in JavaScript. you should not use it to declare your variables or functions. change the variable name from new to something else
Are you sure you didn't do this:
var a = '30';
var b = '40';
Here, I show '30' as a string rather than a number, and I would expect the "+" operator to concatenate two strings. Since this is contrived code, you may not be entirely sure where your variables were initially assign or what type they have. You can check it like this:
var a = '30';
var b = '40';
alert( typeof(a) + '\n' + typeof(b) );
If either of those say 'object' or 'string' rather than 'number' this is your problem. One way this might happen that you didn't expect is with an input. Say you have code like this:
<input id="a" value="30" />
<input id="b" value="40" />
<script language="javascript">
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
</script>
Here, the value of a text input is always a string initially.
If you want to convert a variable to a number first you should use something like myVar - 0 to coerce a numeric operation or the more-formal parseInt() or parseFloat() functions (don't forget the radix parameter for parseInt()). And always check isNaN() on the results.
I'm really surprised that noone has until now suggested the obvious: "Casting" with JavaScript (I set it in quotes, because it is no real casting).
var a = "1"; // string
var b = Number(a); // number
var c = String (b); // string again
a + b; // "11"
b + a; // 2
a + c; // "11"
Now, why is this no real casting? Because you don't create a new variable of type "number" but a new object "Number" and initialize it with something that could be numerical.
One or both is a string. If you get the values from a HTML input or something, they definitely are. Make sure they're both integers by using parseInt:
var newValue = parseInt(a,10) + parseInt(b,10);
Also, 'new' is a keyword. You can't use that for a variable name :)