EVAL function showing unexpected result if prepend Zero (0) - javascript

I am getting an unexpected result from the eval function.
alert(eval(1 + 033))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If I execute eval(1 + 033) it's showing the result as 28.
Does anyone know why this is happening? How can I get it to treat 033 as the number 33 and produce 34 as the result?

If you have a string containing a number with a leading zero and you want that number to be treated as a decimal (base-10), you can use parseInt providing 10 as the second parameter.
parseInt(string, radix);
var str = "033";
var x = parseInt(str, 10);
console.log(x + 1);

033 is the octal representation of (decimal) 27
so eval(1+033) is eval(1+27) is eval(28) is 28

Related

Concat two variable and compare with number

Javascript Code
I am concacting two variables and comparing with a string
Why the alert is true? Why it is not coercing??
var str1 = "2";
var str2 = "3";
var res = str1 + str2 // return 23
console.log(res) // 23
console.log("100") // 100
alert(res > "100") // alerts true instead of false
The value in res is a string. In strings "23" is greater than "100" (looking at the first character).
To further answer your question "why isn't javascript coercing" I'd like to quote a comment from James Thorpe
"Both sides are strings - there is nothing to coerce"
Here's a code example.
console.log (23 > "100") // false
console.log ("23" > "100") // true
First console.log compares number with string - javascript coerces.
Second console.log compares string with string - nothing to coerce
Alert is true because '23' is lexicographically greater than '100' ('2' > '1').
You can use parseInt to convert strings to numbers:
alert(parseInt(res) > 100);
Because you are comparing strings. "100" is lower then "23" because "1"<"2".
You should parse to int if you want numerical comparison, as shown in #jh314 answer.
You can temporarily change the string to their number representation i.e, 23 and 100 and use the comparison operator. Either prefix the values with + to change them to numeric value or use parseInt():
var str1 = "2";
var str2 = "3";
var res = str1 + str2 // return 23
console.log(res) // 23
console.log("100") // 100
alert(+res > +"100")
The value of res is "23" not 23. That means it's a string and therefore when you alert the comparison it compares the first digit of each, 2 > 1 which is true.
As for “why is it not coercing?” - because both operands are strings in both cases, and because both + and > are valid operations on strings.
(Using - (subtract) would cause implicit coercion to number because it doesn’t make sense for strings, but concatenation and addition use the same operator. Welcome to JavaScript!)
Your alert is comparing a string and a string.
Try: alert(res > 100)

parse integer with javascript using parseInt and a radix

I am doing an online test and it asks me to write basic javascript code.
It asks me to parse a numberic string and convert it to a number of a different base. It needs me to return -1 if for whatever reason the conversion cannot be done.
I have written this:
function convert(strNumber, radix) {
var result = parseInt(strNumber, radix);
if(isNaN(result))
{return -1;}
return result;
}
Then it runs my code through various tests and all pass. Except one.
Apparently convert("ASD", 15) should be invalid according to the test and it expects it to be -1.
But Javascript happily converts it to number 10
I tried various things such as to add a try{}catch{} block and other things, but javascript never complains about converting "ASD" to base 15.
Is the test wrong, or is parseInt wrong?
By the way strNumber can be any base under 36.
So for instance:
convert("Z", 36) is 35
As I stated in the comment, parseInt will convert up to the point where it fails. So "A" is valid in that radix and "S" is not. So you would need to add a check.
var nums = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".substr(0, radix)
var re = new RegExp("^[" + nums + "]+$","i")
if (!re.test(strNumber)) {
return -1
}
parseInt is behaving normally and is converting the letter A into 10 in base 15 (similar to how hex uses A for the number 10). The S and D are discarded, as parseInt accepts this type of malformed input.
From the parseInt documentation:
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point.
As per official documentation the parseInt function behaves as following
For radices above 10, the letters of the alphabet indicate numerals
greater than 9. For example, for hexadecimal numbers (base 16), A
through F are used.
and
If parseInt encounters a character that is not a numeral in the
specified radix, it ignores it and all succeeding characters and
returns the integer value parsed up to that point.
Thus to prevent invalid arguments from being parsed they have to be validated first
function convert(strNumber, radix) {
if (isValidRadix(radix) && isValidInteger(strNumber, radix))
return parseInt(strNumber, radix);
return -1;
}
function isValidInteger(str, radix) {
var letters = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'].slice(0,radix);
str = str.toUpperCase();
for (var i=0; i<str.length; i++) {
var s = str.charAt(i);
if (letters.indexOf(s) == -1) return false;
}
return true;
}
function isValidRadix(radix) {
// 16 up to HEX system
return radix > 0 && radix <= 16;
}
console.log(convert("ASD", 15));
console.log(parseInt("ASD", 15));
console.log(convert("AAA", 15));

value more than not read in if condition in javascript

I m getting two textboxes value as 5 and 10.
so i m validating them on the following if condition
var textboxvalue1 = $('#textboxvalue1' + counter).val();
var textboxvalue2 = $('#textboxvalue2' + counter).val();
if (textboxvalue1 < textboxvalue2) {
alert("error");
}
textboxvalue1 = 10
textboxvalue2 = 5
its showing an alert in this case.which it shud nt show.bt when textboxvalue1 is less than 10,it works fine.
Actually your .val() returns string you try to convert it as integer so use parseInt() in your context and check.
The parseInt() function parses a string and returns an integer.
Note:
The radix parameter is used to specify which numeral system to be
used, for example, a radix of 16 (hexadecimal) indicates that the
number in the string should be parsed from a hexadecimal number to a
decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal) If the
string begins with "0", the radix is 8 (octal). This feature is
deprecated If the string begins with any other value, the radix is 10
(decimal)
var textboxvalue1= parseInt($('#textboxvalue1'+counter).val(), 10);
var textboxvalue2= parseInt($('#textboxvalue2'+counter).val(), 10);
if (textboxvalue1 < textboxvalue2) {
alert("error");
}
You have to convert your input strings to numbers like this:
var textboxvalue1=parseInt($('#textboxvalue1'+counter).val());
var textboxvalue2=parseInt($('#textboxvalue2'+counter).val());
The values are being interpreted as strings by JavaScript, not numbers. Wrap them in parseInt or parseFloat before comparing them.
Use ParseInt Because var return string default. Or you can use parseFloat
var textboxvalue1= parseInt($('#textboxvalue1'+counter).val(), 10);
var textboxvalue2= parseInt($('#textboxvalue2'+counter).val(), 10);
if (textboxvalue1 < textboxvalue2) {
alert("error");
}

JavaScript Detecting Octal Value at Different Scenario

var x = 02345;
var y = x.toString();
alert(y);
I realized that there is a problem converting leading zeroes number to string in JavaScript using the toString() method.
As you can see from the output of the code above, the output is 1253 instead of the supposedly 02345.
If the leading zero is removed, the code will work as expected, why? What is happening with the code above so I can change it to work as expected.
var x = 2345;
var y = x.toString();
alert(y);
EDIT : The reason I asked this question is because I have two different codes that work differently despite being very similar. After reading that this question has nothing to do with the toString() method, why does the first set of code below not detect the number as an octal value but the second set of code does.
var num=window.prompt(); // num = 0012222
var str = num.toString();
var result = [str[0]];
for(var x=1; x<str.length; x++)
{
if((str[x-1]%2 === 0)&&(str[x]%2 === 0))
{
result.push('-', str[x]);
}
else
{
result.push(str[x]);
}
}
alert(result.join('')); //Outputs : 0-012-2-2-2
The other code :
function numberDash(num) {
var stringNumber = num.toString();
var output = [stringNumber[0]];
for (var i = 1; i < stringNumber.length; i++) {
if (stringNumber[i-1] % 2 === 0 && stringNumber[i] % 2 === 0) {
output.push('-', stringNumber[i]);
} else {
output.push(stringNumber[i]);
}
}
return output.join('');
}
numberDash(0012222) // Outputs : "52-6-6";
Many JavaScript engines add octal numeric literals to the specification. The leading zero indicates octal (base 8). 2345 in base 8 (octal) is 1253 in base 10 (decimal):
Octal Decimal
----- --------------------
2 2 * 8 * 8 * 8 = 1024
3 3 * 8 * 8 = 192
4 4 * 8 = 32
5 5
----- --------------------
2345 1253
You can disable that using strict mode. See §B.1.1 of the specification. Doing so makes 02345 a syntax error.
So it's nothing to do with toString, it's just that the 02345 in your code isn't the value you expect.
Re your updated question:
why does the first set of code below not detect the number as an octal value but the second set of code does
Because in the first code, you're not dealing with a number, you're dealing with a string. window.prompt returns a string, not a number, even if what you type in is all digits.
Even if you converted the string to a number via Number(num) or +num, the rules for runtime string->number conversion are different from the rules for parsing JavaScript source code.
var x = 02345;
var y = x.toString("8");
alert(y);
This will give you 2345
Leading zero is interpreted as octal value.
If you need number converted to string with leading zero, use my method but simply modify it like this var y = "0" + x.toString("8")

Get first two digits of a string, support for negative 'numbers'

I have the following strings in JavaScript as examples:
-77.230202
39.90234
-1.2352
I want to ge the first two digits, before the decimal. While maintaining the negative value. So the first one would be '-77' and the last would be '-1'
Any help would be awesome!
Thank you.
You can simply use parseInt().
var num = parseInt('-77.230202', 10);
alert(num);
See it in action - http://jsfiddle.net/ss3d3/1/
Note: parseInt() can return NaN, so you may want to add code to check the return value.
Late answer, but you could always use the double bitwise NOT ~~ trick:
~~'-77.230202' // -77
~~'77.230202' // 77
~~'-77.990202' // -77
~~'77.930202' // 77
No octal concerts with this method either.
try this, but you'd have to convert your number to a string.:
var reg = /^-?\d{2}/,
num = -77.49494;
console.log(num.toString().match(reg))
["-77"]
var num = -77.230202;
var integer = num < 0 ? Math.ceil(num) : Math.floor(num);
Also see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math.
Do you just want to return everything to the left of the decimal point? If so, and if these are strings as you say, you can use split:
var mystring = -77.230202;
var nodecimals = mystring.split(".", 1);

Categories

Resources