When I do this:
var x = parseInt("–2147483648");
console.log(x);
I get the value as:
NaN
Why does this happen?
I want to test if a number is in the range of C (int), so I am doing the above, but it does not work. Also, I want to do this for C (long), is there a way to this?
For example:
If I do:
var x = parseInt("-9223372036854775808");
console.log(x);
Now, I know that (-+)2^53 is the limit of numbers in Javascript. Is there some other way to test if the given value in a form is actually in the range of long or int?
It should work fine, the problem is that you're using the wrong character, an ndash – vs a hyphen -:
var x = parseInt("-2147483648");
console.log(x);
If you copy/paste that you'll see that it works now.
Related
I need to compare an array length with the text displaying numbers in the UI. I stored the array length in 'X' variable, whereas the text in 'len' variable.
I need to reduce the X by 3 and compare with the string 'len'.
EG: Len value is '+31' which is string. and X value is 34.
Please help me out to compare both the values. I tried converting both to string or int. Nothing helps me out.
var len=createMenu.numPrivSelected.getText();
var x=createMenu.returnLength(createMenu.selectedpriv);
console.log(len+","+x-3);
expect(len).toEqual(x);
returnLength() is a method which returns the length of the element.
numPrivSelected is an element which returns text as '+31'.
Output is:
NaN
Expected '+31' to equal 34.
Well first, your console.log is return NaN because it's trying to do arithmetic on the string.
console.log(len+","+x-3);
It would go like this:
len+","+x-3
"+31,"+x-3
"+31,34"-3
And obviously "string minus integer" won't work, so that's why it resulting in NaN (Not a Number).
Secondly, if you want to compare two numbers you need to make sure they're both numbers. The + sign in len makes it a string, and it can't be converted to a number directly. First you'll have to remove the plus sign. Here's your code, adjusted to fix the obvious errors that I can see:
var len=createMenu.numPrivSelected.getText();
var x=createMenu.returnLength(createMenu.selectedpriv);
len = len.replace("+","");
x -= 3;
console.log(len+","+x);
expect(len).toEqual(x);
I tried as below and it worked,
var len;
var x;
createMenu.returnLength(createMenu.selectedpriv).then(function(num){
len=num-3;
console.log(len);
});
createMenu.numPrivSelected.getText().then(function(text){
x=text.replace("+","");
console.log(x);
});
expect(len).toEqual(x);
Below code should work,
var len = createMenu.returnLength(createMenu.selectedpriv).then(function(num){
return num-3;
});
var x = createMenu.numPrivSelected.getText().then(function(text){
return parseInt(text.replace("+",""));
});
expect(len).toEqual(x);
I am trying to get an 8 decimal output from the following function.
The following function multiplies an input by 2 and then updates this input with the wagerUpdate variable. I would like this outputted number to have 8 decimal places.
For example: if input number is 0.00000001 (this code is for a bitcoin website), then I would like output number to be 0.00000002. For some reason the code below is not working properly as the output number is in the format of 2e-8 without the .toFixed(8) code. Please help if you are able to. Thank you so much.
<script>
function MultiplyWagerFunction() {
var wager = document.getElementById("wagerInputBox").value;
var wagerUpdate = wager*2;
document.getElementById("wagerInputBox").value = +wagerUpdate.toFixed(8);
}
</script>
If you remove the + before wagerUpdate.toFixed(8) it should work fine. wagerUpdate has already be converted to a number when you multiplied it by 2 so there should be no need for the unary +
var a = "0.00000001";
var b = a*2;
console.log(b.toFixed(8));
console.log(+b.toFixed(8));
^ see the difference.
The reason it doesn't work is because what you are doing is equivalent to:
+(b.toFixed(8))
because of the precedence of the operators (member access . is higher than unary +). You are converting b to a string with .toFixed and then converting it back into a number with + and then converting it back into a string again! (this time with the default toString behavior for numbers giving you exponential notation)
Just remove + from +wagerUpdate.toFixed(8); and you would be good.
Instead of:
document.getElementById("wagerInputBox").value = +wagerUpdate.toFixed(8);
try:
document.getElementById("wagerInputBox").innerHTML = +wagerUpdate.toFixed(8);
Why I say so is may be when you set value, browser tries to convert to best possible outcome. But, inner HTML should take the string equivalent!
When I use p=10000 ,r=15 and n=60 in the below ...
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100).toFixed(2));
x = 237.9 instead of 237.90.
If the combo of p, r and n result in a number that is not $xx.x", then the code snippet works fine ...ie. formats to 2 decimal places.
But why is it displaying 237.9 instead of 237.90?
When you call number.toFixed(2), you do indeed get a string representation of the number with two decimal digits:
var number = 237.9;
number.toFixed(2); // '237.90'
However, when you then use parseFloat on this, you convert it back to a number again; since a number does not contain information about the number of zeros to display, the last zero is dropped as it is printed:
parseFloat(number.toFixed(2)); // 237.9
To avoid this, simply don't convert your string back into a float, but use it as a string.
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100)).toFixed(2);
p=10000,r=15, n=60;
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100)).toFixed(2);
console.log(x)
Add toFixed after all operations. You need string, basically...
I am just dipping my toe into the confusing world of javascript, more out of necessity than desire and I have come across a problem of adding two integers.
1,700.00 + 500.00
returns 1,700.00500.00
So after some research I see that 1,700.00 is being treated as a string and that I need to convert it.
The most relevant pages I read to resolve this were this question and this page. However when I use
parseInt(string, radix)
it returns 1. Am I using the wrong function or the an incorrect radix (being honest I can't get my head around how I decide which radix to use).
var a="1,700.00";
var b=500.00;
parseInt(a, 10);
Basic Answer
The reason parseInt is not working is because of the comma. You could remove the comma using a regex such as:
var num = '1,700.00';
num = num.replace(/\,/g,'');
This will return a string with a number in it. Now you can parseInt. If you do not choose a radix it will default to 10 which was the correct value to use here.
num = parseInt(num);
Do this for each of your string numbers before adding them and everything should work.
More information
How the replace works:
More information on replace at mdn:
`/` - start
`\,` - escaped comma
`/` - end
`g` - search globally
The global search will look for all matches (it would stop after the first match without this)
'' replace the matched sections with an empty string, essentially deleting them.
Regular Expressions
A great tool to test regular expressions: Rubular and more info about them at mdn
If you are looking for a good tutorial here is one.
ParseInt and Rounding, parseFloat
parseInt always rounds to the nearest integer. If you need decimal places there are a couple of tricks you can use. Here is my favorite:
2 places: `num = parseInt(num * 100) / 100;`
3 places: `num = parseInt(num * 1000) / 1000;`
For more information on parseInt look at mdn.
parseFloat could also be used if you do not want rounding. I assumed you did as the title was convert to an integer. A good example of this was written by #fr0zenFry below. He pointed out that parseFloat also does not take a radix so it is always in base10. For more info see mdn.
Try using replace() to replace a , with nothing and then parseFloat() to get the number as float. From the variables in OP, it appears that there may be fractional numbers too, so, parseInt() may not work well in such cases(digits after decimal will be stripped off).
Use regex inside replace() to get rid of each appearance of ,.
var a = parseFloat('1,700.00'.replace(/,/g, ''));
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = a+b;
This should give you correct result even if your number is fractional like 1,700.55.
If I go by the title of your question, you need an integer. For this you can use parseInt(string, radix). It works without a radix but it is always a good idea to specify this because you never know how browsers may behave(for example, see comment #Royi Namir). This function will round off the string to nearest integer value.
var a = parseInt('1,700.00'.replace(/,/g, ''), 10); //radix 10 will return base10 value
var b = parseInt('500.00'.replace(/,/g, ''), 10);
var sum = a+b;
Note that a radix is not required in parseFloat(), it will always return a decimal/base10 value. Also, it will it will strip off any extra zeroes at the end after decimal point(ex: 17500.50 becomes 17500.5 and 17500.00 becomes 17500). If you need to get 2 decimal places always, append another function toFixed(decimal places).
var a = parseFloat('1,700.00'.replace(/,/g, ''));
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = (a+b).toFixed(2); //change argument in toFixed() as you need
// 2200.00
Another alternative to this was given by #EpiphanyMachine which will need you to multiply and then later divide every value by 100. This may become a problem if you want to change decimal places in future, you will have to change multiplication/division factor for every variable. With toFixed(), you just change the argument. But remember that toFixed() changes the number back to string unlike #EpiphanyMachine solution. So you will be your own judge.
try this :
parseFloat(a.replace(/,/g, ''));
it will work also on : 1,800,300.33
Example :
parseFloat('1,700,800.010'.replace(/,/g, '')) //1700800.01
Javascript doesn't understand that comma. Remove it like this:
a.replace(',', '')
Once you've gotten rid of the comma, the string should be parsed with no problem.
I have two variables holding integer values:
x = 36,000;
y = 18,045.40;
this is how i subtract:
z = parseInt(x) - parseInt(y);
the result is 15.
If i remove the parseInt the result is 'Nan'.
How do I go about subtracting x with y without rounding off or removing thousands?
many thanks.
Don't put commas in your numbers.
The code you have posted won't even run. I would recommend pulling the ,s out of your numbers and using parseFloat instead. This appears to give the result you want. Demo here:
http://jsfiddle.net/yVWA9/
code:
var x = 36000;
var y = 18045.40;
alert(parseFloat(x) - parseFloat(y));
There is no separator for thousands in Javascript. Your variables are either holding strings and not integer values or you are getting syntax error.
If you have strings and they cannot be changed (like received from service, etc.) then try this:
x = "36,000";
y = "18,045.40";
// remove commas and convert to numbers
function norm(num) { return +num.replace(',', ''); }
console.log(norm(x) - norm(y));