value more than not read in if condition in javascript - 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");
}

Related

Truncate a number

function truncDigits(inputNumber, digits) {
const fact = 10 ** digits;
return Math.trunc(inputNumber * fact) / fact;
}
truncDigits(27624.399999999998,2) //27624.4 but I want 27624.39
I need to truncate a float value but don't wanna round it off. For example
27624.399999999998 // 27624.39 expected result
Also Math.trunc gives the integer part right but when you Math.trunc value 2762439.99 it does not give the integer part but gives the round off value i.e 2762434
Probably a naive way to do it:
function truncDigits(inputNumber, digits) {
return +inputNumber.toString().split('.').map((v,i) => i ? v.slice(0, digits) : v).join('.');
}
console.log(truncDigits(27624.399999999998,2))
At least it does what you asked though
Try this:
function truncDigits(inputNumber, digits){
return parseFloat((inputNumber).toFixed(digits));
}
truncDigits(27624.399999999998,2)
Your inputs are number (if you are using typescript). The method toFixed(n) truncates your number in a maximum of n digits after the decimal point and returns it as a string. Then you convert this with parseFloat and you have your number.
You can try to convert to a string and then use a RegExp to extract the required decimals
function truncDigits(inputNumber: number, digits: number) {
const match = inputNumber.toString().match(new RegExp(`^\\d+\\.[\\d]{0,${digits}}`))
if (!match) {
return inputNumber
}
return parseFloat(match[0])
}
Note: I'm using the string version of the RegExp ctor as the literal one doesn't allow for dynamic params.

EVAL function showing unexpected result if prepend Zero (0)

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

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));

Addition operator not working in JavaScript

Addition operator isn't working for me in Javascript. If I do 5+5, it gives me 55 instead of 10. How can I fix this?
var numberOne = prompt (Enter first number.);
if (numberOne > 0.00001) {
var numberTwo = prompt(Enter the second number.);
if (numberTwo > 0.00001) {
var alertAnswer = alert (numberOne + numberTwo);
}
}
You're reading in strings, and concatenating them. You need to convert them to integers with parseInt.
IE:
var numberOne = parseInt(prompt("Enter first number."), 10);
There are two main changes that need to take place. First, the prompts must use Strings. Second, you must parse the user's String input to a number.
var numberOne = prompt ("Enter first number.");
if (numberOne > 0.00001) {
var numberTwo = prompt("Enter the second number.");
if (numberTwo > 0.00001) {
var alertAnswer = alert (parseInt(numberOne,10) + parseInt(numberTwo,10));
}
you need to use parseInt
as in
var a = parseInt(prompt("Please enter a number"));
Just for completeness: a potential problem with parseInt() (in some situations) is that it accepts garbage at the end of a numeric string. That is, if I enter "123abc", parseInt() will happily return 123 as the result. Also, of course, it just handles integers — if you need floating-point numbers (numbers with fractional parts), you'll want parseFloat().
An alternative is to apply the unary + operator to a string:
var numeric = + someString;
That will interpret the string as a floating-point number, and it will pay attention to trailing garbage and generate a NaN result if it's there. Another similar approach is to use the bitwise "or" operator | with 0:
var numeric = someString | 0;
That gives you an integer (32 bits). Finally, there's the Number constructor:
var numeric = Number( someString );
Also allows fractions, and dislikes garbage.

javascript if number greater than number [duplicate]

This question already has answers here:
issue with comparing two numbers in javascript
(5 answers)
Closed 4 months ago.
I have this javascript function to validate if a number is greater than another number
function validateForm() {
var x = document.forms["frmOrder"]["txtTotal"].value;
var y = document.forms["frmOrder"]["totalpoints"].value;
if (x > y) {
alert("Sorry, you don't have enough points");
return false;
}
}
It's not working for some reason.
If I do alert(x) I get 1300, and alert(y) gives 999
This works....
function validateForm() {
var x = 1300;
var y = 999;
if (x > y) {
alert("Sorry, you don't have enough points");
return false;
}
}
You should convert them to number before compare.
Try:
if (+x > +y) {
//...
}
or
if (Number(x) > Number(y)) {
// ...
}
Note: parseFloat and pareseInt(for compare integer, and you need to specify the radix) will give you NaN for an empty string, compare with NaN will always be false, If you don't want to treat empty string be 0, then you could use them.
You're comparing strings. JavaScript compares the ASCII code for each character of the string.
To see why you get false, look at the charCodes:
"1300".charCodeAt(0);
49
"999".charCodeAt(0);
57
The comparison is false because, when comparing the strings, the character codes for 1 is not greater than that of 9.
The fix is to treat the strings as numbers. You can use a number of methods:
parseInt(string, radix)
parseInt("1300", 10);
> 1300 - notice the lack of quotes
+"1300"
> 1300
Number("1300")
> 1300
You can "cast" to number using the Number constructor..
var number = new Number("8"); // 8 number
You can also call parseInt builtin function:
var number = parseInt("153"); // 153 number
Do this.
var x=parseInt(document.forms["frmOrder"]["txtTotal"].value);
var y=parseInt(document.forms["frmOrder"]["totalpoints"].value);

Categories

Resources