javascript bigger than if statement not working correctly - javascript

I am no expert in javascript, so hope someone can help me out.
I have the following code, but for some reason it always thinks the statement is true
delvNum=document.getElementById("deliveryNum").value;
delvQTY=document.getElementById("delvQTY"+id).value;
orderQTY=document.getElementById("orderQTY"+id).value;
if (delvQTY>orderQTY)
{
alert("Can't deliver more than " + orderQTY + ", you are trying to deliver " + delvQTY + ". Please fix!");
document.getElementById("delvQTY"+id).focus();
return;
}
The error message does show the quantity of each var, and is correctly being passed through.

You are comparing strings and not numbers.
Use parseInt or parseFloat
if (parseFloat(delvQTY)>parseFloat(orderQTY))
or
if (parseInt(delvQTY,10)>parseInt(orderQTY,10))

You're doing a string comparison, not number comparison and, for example, "9">"1111" is true.
You need to parse your values :
if (parseFloat(delvQTY)>parseFloat(orderQTY))
See parseFloat.

You need to make sure delvQTY and orderQTY are Number before you can do > comparison.
var delvValue = parseInt(delvQTY, 10); for converting to integers.
Or for floating point numbers: var delvValue = parseFloat(delvQTY);

You're comparing the string values, rather than numerical ones. You should say:
delvNum = parseInt(document.getElementById("deliveryNum").value, 10);
(assume you are dealing with integers, else use parseFloat).
Note the 10 to say you're dealing with base 10 - without it, if someone types a leading zero then you'll get baffling results.

Related

Updated post: How do I get a JavaScript factorial programs' loop to show the working used? See requirements

this is my second post today as the original wasn’t clear and I was urged to repost because despite getting some good answers they did not fit the requirements of the code. I have been challenged to write a program in JavaScript that allows the user to perform several tasks, one of which is to ask the user for a number and calculate the factorial of that number and then display it in the format listed in the requirements. As I do not know much about Java script I used already asked questions and managed to get the calculation to work but could not figure out how to get the required output whilst still meeting the requirements.
Requirements:
• Can only use the provided variables Number (variable initialised as 0 to hold user input) Factorial (variable initialised to 1 to hold value of calculated factorial) Count (variable to hold number of times loop is executed for performing factorial calculation). This is a limitation set by the challenge and not me
• Cannot use fancy libraries
• Need to use a loop solution for the output. The answers on the other post required introducing new variables, perhaps it is my lack of understanding but perhaps the poorly written pseudo code I have obtained since the last post may help.
• Be output in the format: (it is an alert so that part of the program is fine)
The factorial of 5 is 5*4*3*2*1=120
OR
5! is 5*4*3*2*1=120
Poorly written pseudo code:
Code:
//prompts the user for a positive number
var number = parseInt(prompt("Please enter a positive number"));
console.log(number);
//checks the number to see if it is a string
if (isNaN(number))
{
alert("Invalid. Please Enter valid NUMBER")
}
//checks the number to see if it is negaive
else if (number < 0)
{
alert("Please Enter valid positive number");
}
//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
let factorial = 1;
for (count = 1; count <= number; count++) {
factorial *= count;
}
//Sends the inital number back to the user and tells them the factorial of that number
alert("The factorial of " + number + " is " + factorial + ".");
}
I know there are many similar questions, including my first post which this one now succeeds as I looked around and used them to help me get this far but it is getting the output into the required format that I'm struggling with. I am told it is possible with a loop but do not know where to begin implementing that and I'm only allowed to use that solution.
Again, I would like to apologise for my first post, the given answers would work great if not for the incredibly ridiculous restrictions set by the challenge provider, who is also responsible for giving me rubbish pseudo code, which isn't what I'm going for but I am using to consider the loop.
I appreciate the time it takes to read this amd provide solutions so I will go back and try and mark all working answers in the last post for any normal problems people might search for answers for.
This is a bit of a dirty hack but it should satisfy the condition that no other variables than number, count, and factorial are used.
let number = 5;
let factorial = 120;
// ^ Do your own calculation for this
alert(`The factorial of ${number} is ${Array.from(Array(number + 1).keys()).slice(1).reverse().join("*")}=${factorial}`)
So what is going on here?
We use an interpolated template string to produce the desired output, expressions inside ${these things} are evaluated as strings. And what is the mess we put in there?
Array.from(Array(number + 1).keys())
The expression above creates the array [0,1,2,3,4,5].
.slice(1) gives us [1,2,3,4,5]
.reverse() gives us [5,4,3,2,1]
join("*") gives us "5*4*3*2*1"
Which when all put together gives us The factorial of 5 is 5*4*3*2*1=120
And voila! The output is printed in the desired format without introducing any new variables.
Edit: Oh and you do not need to use an interpolated string for this. You may as well concatenate regular strings together as you have done in your question. e.g.
"The factorial of " + factorial + " is " + Array.from(Array(number + 1).keys()).slice(1).reverse().join("*") + "=" + factorial

Why I can't convert string to number without losing precision in JS?

We all know that +, Number() and parseInt() can convert string to integer.
But in my case I have very weird result.
I need to convert string '6145390195186705543' to number.
let str = '6145390195186705543';
let number = +str; // 6145390195186705000, but should be: 6145390195186705543
Could someone explain why and how to solve it?
Your number is above the Number.MAX_SAFE_INTEGER (9,007,199,254,740,991), meaning js might have a problem to represent it well.
More information
You are outside the maximum range. Check in your console by typing Number.MAX_SAFE_INTEGER
If you want a number outside this range, take a look into BigInt that allows to define numbers beyond the safe range
https://developers.google.com/web/updates/2018/05/bigint
Read the documentation well before using it since the usage is different than usual
I am guessing this is to solve the plusOne problem in leetcode. As others have answered, you cannot store value higher than the max safe integer. However you can write logic to add values manually.
If you want to add one to the number represented in the array, you can use the below function. If you need to add a different value, you need to tweak the solution a bit.
var plusOne = function(digits) {
let n = digits.length, carry=0;
if(digits[n-1]<9){
digits[n-1] +=1;
} else{
digits[n-1] = 0;
carry=1;
for(let i=n-2;i>=0;i--){
if(digits[i]<9){
digits[i]+=1;
carry=0;
break;
}else{
digits[i]=0;
}
}
if(carry>0){
digits.unshift(carry);
}
}
return digits;
};
Short answer: Your string represents a number to large to fit into the JavaScript number container.
According to the javascript documentation the maximum safe number is 2^53 which is 9007199254740992 source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
When you try and convert your number you're creating an overflow exception so you get weird results.

How to get an 8 decimal output?

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!

Javascript convert string to integer

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.

How to compare locale dependent float numbers?

I need to compare a float value entered in a web form against a range. The problem is that the client computers may have various locale settings, meaning that user may use either "." or "," to separate the integer part from decimal one.
Is there a simple way to do it? As it is for an intranet and that they are only allowed to use IE, a VBScript is fine, even if I would prefer to use JavaScript.
EDIT: Let me clarify it a bit:
I cannot rely on the system locale, because, for example, a lot of our french customers use a computer with an english locale, even if they still use the comma to fill data in the web forms.
So I need a way to perform a check accross multiple locale "string to double" conversion.
I know that the raise condition is "what about numbers with 3 decimal digits", but in our environment, this kind of answer never happen, and if it happens, it will be threated as an out of range error due to the multiplication by a thousand, so it's not a real issue for us.
In Javascript use parseFloat on the text value to get a number. Similarly in VBScript use CDbl on the text value. Both should conform to the current locale settings enforce for the user.
This code should work:
function toFloat(localFloatStr)
var x = localFloatStr.split(/,|\./),
x2 = x[x.length-1],
x3 = x.join('').replace(new RegExp(x2+'$'),'.'+x2);
return parseFloat(x3);
// x2 is for clarity, could be omitted:
//=>x.join('').replace(new RegExp(x[x.length-1]+'$'),'.'+x[x.length-1])
}
alert(toFloat('1,223,455.223')); //=> 1223455.223
alert(toFloat('1.223.455,223')); //=> 1223455.223
// your numbers ;~)
alert(toFloat('3.123,56')); //=> 3123.56
alert(toFloat('3,123.56')); //=> 3123.56
What we do is try parsing using the culture of the user and if that doesn't work, parse it using an invariant culture.
I wouldn't know how to do it in javascript or vbscript exactly though.
I used KooiInc's answer but change it a bit, because it didn't reckon with some cases.
function toFloat(strNum) {
var full = strNum.split(/[.,]/);
if (full.length == 1) return parseFloat(strNum);
var back = full[full.length - 1];
var result = full.join('').replace(new RegExp(back + '$'), '.' + back);
return parseFloat(result);
}
Forbid using any thousands separator.
Give the user an example: "Reals should look like this: 3123.56 or 3123,56". Then simply change , to . and parse it.
You can always tell user that he did something wrong with a message like this:
"I don't understand what you mean by "**,**,**".
Please format numbers like "3123.56."

Categories

Resources