JavaScript praseInt("3e3", 10) gives answer 3 - javascript

My task to prompt for a number. And loop till its a number
do {
num=prompt ("Please enter a number:");
if (parseInt(num,10)) {
if (typeof num !=="number") {
if (!isNaN(num)) {
stop=1;
}
}
}
} while (stop != 1);
When I enter "3e3" it works. Y?
how do i fix the praseInt("3e3", 10)?

Check it with regular expression such as /^\d+$/.
if (/^\d+$/.test(num)) {
// it's an integer
} else {
// it's not an integer
}

parseInt will take the first characters of the string until it finds one that it's numeric (or reaches the end).
With that in mind, 3e3 reads the first 3 and discards the rest.
That said, your logic is flawed: parseInt returns the number, whereas you seem to be treating it like it were changing it.

That's because parseInt ignores anything after (and including) first invalid character (step 11.)
If you want to reject things like 3e3, then you can simply test whether the string contains decimals only by doing /^\s*\d+\s*$/.test(num).
If you want to process things like 3e3, then you can simply use unary + operator to convert a string to a number, something like +num. (This will accept strings like 4.2e+42 or 0x2A.)

Related

How to check if number is correct 16x based value?

For examle I need to check string '69S0' - is it correct a 16x based number. I do not need to parse just check true or false.
So, what is an effcient way to do this?
You can check to see if the string contains any invalid digits. The valid digits are 0-9 and ABCDEF, so:
if (/^[0-9a-f]+$/i.test(theString)) {
// yes, valid hex
} else {
// not valid hex
}
Alternatively, you could parse the string using the Number function (note this logic is the other way around):
if (isNaN(Number("0x" + theString)) {
// not valid hex
} else {
// yes, valid hex
}
That works because Number accepts certain number base prefixes (0x = hex, 0b = binary, and 0o = octal), and returns NaN if the entire string isn't a valid number using that number base. (And unlike Number(""), which returns 0, Number("0x") returns NaN, so it'll work if theString is blank, too.)
In comments you mentioned that you couldn't rely on parseInt, and you're right: Instead of throwing an error or returning NaN if there's an invalid digit, parseInt just stops parsing and returns what it found at the beginning of the string. (Details in this answer.)

Number base conversion with exception handling

I have a function that converts a string representation of number of any valid number base and its radix. How do I correctly handle invalid numbers (like using A-K chars in bases < 11)? In invalid cases, I would like to return -1.
So far, I was able to achieve some degree of success with isNan() check, but it breaks on decimal base (convert("5A6E", 10)).
My code so far:
function convert(strNumber, radix) {
a = parseInt(strNumber, radix)
if(isNaN(a)){
return -1
}
else {
return a
}
}
In your breakage example "5A6E" you get back 5 because that's how parseInt works - see the examples in the documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
At the bottom of the above page, you will find a section titled "A stricter parse function" it appears to do what you are looking for using RegEx.
Update: In thinking about this further, the "Stricker parse function" is only going to work for base 10. To be more flexible you should add a function that looks at the radix, and based on that, checks for invalid characters in strNumber, returning -1 if any are found and calling parseInt if not.
For instance, if radix = 2, all characters except 0 and 1 are invalid. If it's 11, all characters but 0-9 and 'a' are invalid.
Tedious, but it will do what you want.

javascript, parseInt behavior when passing in a float number

I have the following two parseInt() and I am not quite sure why they gave me different results:
alert(parseInt(0.00001)) shows 0;
alert(parseInt(0.00000001)) shows 1
My guess is that since parseInt needs string parameter, it treats 0.00001 as ""+0.00001 which is "0.00001", therefore, the first alert will show 0 after parseInt. For the second statement, ""+0.00000001 will be "1e-8", whose parseInt will be 1. Am I correct?
Thanks
I believe you are correct.
parseInt(0.00001) == parseInt(String(0.00001)) == parseInt('0.00001') ==> 0
parseInt(0.00000001) == parseInt(String(0.00000001)) == parseInt('1e-8') ==> 1
You are correct.
parseInt is intended to get a number from a string. So, if you pass it a number, it first converts it into a string, and then back into a number. After string conversion, parseInt starts at the first number in the string and gives up at the first non-number related character. So "1.e-8" becomes "1"
If you know you are starting with a string, and are just trying to get an Integer value, you can do something like.
Math.round(Number('0.00000001')); // 0
If you know you have a floating point number and not a string...
Math.round(0.00000001); // 0
You can also truncate, ceil(), or floor the number
parseInt takes each character in the first argument (converted to a string) that it recognizes as a number, and as soon as it finds a non-numeric value it ignores that value and the rest of the string. (see MDN second paragraph under "Description")
Therefore it's likely that parseInt(0.00000001) === parseInt(String(0.00000001)) === parseInt("1e-8"), which would only extract the 1 from the string yielding parseInt("1") === 1
However, there's another possibility:
From Mozilla developer network:
parseInt(string, radix);
for the string argument (emphasis added): "The value to parse. If string is not a string, then it is converted to one. Leading whitespace in the string is ignored."
I think this possibility is less likely, since String(0.00000001) does not yield NAN.

Why is the number converted to a string (basic Javascript function)

I have this function (going trough the Eloquent Javascript Tutorial chapter 3):
function absolute(number) {
if (number < 0)
return -number;
else
return number;
}
show(absolute(prompt("Pick a number", "")));
If I run it and enter -3 the output will be 3 as expectet but if I enter just 3 the output will be "3" (with double quotes). I can get around by changing
return number;
to
return Number(number);
but why is that necessary? What am I missing?
prompt() always returns a string, but when you enter a negative number, it is handed to the -number call and implicitly converted to a Number. That doesn't happen if you pass it a positive, and the value received by prompt() is returned directly.
You can, as you discovered, cast it with Number(), or you can use parseInt(number, 10), or you could do -(-number) to flip it negative, then positive again, or more obviously as pointed out in comments, +number. (Don't do --number, which will cast it to a Number then decrement it)
Javascript is not strongly typed.
number comes from the prompt() function, which returns a string.
Since you aren't doing anything to change its type, it remains a string.
-number implicitly converts and returns an actual number.
If you have a string that needs to be converted to a number, please do the following:
var numString = '3';
var num = parseInt(numString);
console.log(num); // 3
JavaScript performs automatic conversion between types. Your incoming "number" is most likely string (you can verify by showing result of typeof(number)).
- does not take "string" as argument, so it will be converted to number first and than negated. You can get the same behavior using unary +: typeof(+ "3") is number when typeof("3") is string.
Same happens for binary - - will convert operands to number. + is more fun as it work with both strings "1"+"2" is "12", but 1+2 is 3.

JavaScript Number preserve leading 0

I have a problem, I build a very simple javascript search for postal codes.
I am using JS Numbers because I want to check if the passed number (search term) is less||equal or more||equal to the max and min.
value >= splitZips[0] && value <= splitZips[1]
But the Javascript Number var type deletes leading 0, which is a problem because I have postal codes like 01075 and also postal codes like 8430. So it can not find the small 4 digit codes.
Any idea how to fix this?
Represent them as a String. Outside of strict mode, a leading zero denotes an octal number otherwise.
Also, why would a leading zero have any significance when calculating numbers? Just use parseInt(num, 10) if you need to.
Store and display the postcodes as strings, thus retaining the leading zeros. If you need to make a numerical comparison convert to number at the time. The easiest way to convert is with the unary plus operator:
var strPC = "01745",
numPC = +strPC;
alert(numPC === +"01745"); // true
+value >= +splitZips[0] && +value <= +splitZips[1];
// etc.
Before you start comparing you might want to ensure the entered value actually is numeric - an easy way to be sure it is a four or five digit code with or without leading zeros is with a regex:
/^\d{4,5}$/.test(searchTerm) // returns true or false
Instead a parseInt you could use type casting :)
"0123">"122" // false
+"0123">"122" // true | that means: 123>"122"
Btw, what more you can use a each of bitwise operators :
~~"0123"
"0123"|0
"0123"&"0123"
"0123">>0
"0123"<<0
With the same effect :)

Categories

Resources