JavaScript operator + doesn't work normally - javascript

Need some help with this simple code, if we will input the value for "work experience" for example 3 and the salary "1000" by the condition the salary should add 10% to the initial salary so the result should be "1100" but in my formula it shows the result like 1000250, i observed if i change the symbol "+" into "-" it shows correctly "900", what i am doing wrong?
if (age>=3 && age<10) {
var increase_1;
var salary_2;
increase_1=(salary*10)/100;
salary_2=salary+increase_1;
document.write('<h4>' +'Proceeding from work experience the new salary was increase by 10%:\t'+ +salary_2+ '<\h4>');
Also if i am using the salary a defended value like "salary=1000;" the program works with no problem.. waiting for some answers, thx
<html>
<head>
</head>
<script>
function doStuff()
{
var nameAge = document.getElementById("ageInput");
var age = nameAge.value;
var nameSalary = document.getElementById("salaryInput");
var salary = nameSalary.value;
document.write('<h2>' +'Age experience:\t'+ +age+ '<\h2>');
document.write('<h2>' +'Starting salary ($):\t'+ +salary+ '<\h2>');
if (age>=3 && age<10) {
var increase_1;
var salary_2;
increase_1=(salary*10)/100;
salary_2=salary+increase_1;
document.write('<h4>' +'Proceeding from work experience the new salary was increase by 10%:\t'+ +salary_2+ '<\h4>');
}
else if (age>=10 && age<20){
var increase_2;
var salary_3;
increase_2=(salary*25)/100;
salary_3=salary+increase_2;
document.write('<h4>' +'Proceeding from work experience the new salary was increase by 25%:\t'+ +salary_3+ '<\h4>');
}
else if (age>=20){
document.write('<h4>' +'Proceeding from work experience you get a prize:'+ '<\h4>');
document.write('<img src="http://3.bp.blogspot.com/-2T_AGEs19_4/T_c2ERHsJeI/AAAAAAAIK9E/MGAQAa9ppDE/s800/2013-Mercedes-G-Class-AMG-011.jpg">');
}
else {
document.write('<h4>' +'Proceeding from work experience the salary is:\t' +salary+'<\h4>');
}
}
</script>
<h1>Please enter your work experience(years)</h1>
<input id="ageInput" type="text">
<h1>Please enter your salary($)</h1>
<input id="salaryInput" type="text">
<input type="button" value="Submit" onClick="doStuff()">
</html>

JavaScript is seeing some values which are taken from input boxes as strings of text rather than numeric values, and simple concatenating them.
If you are reading a value from a input box and want to use it in an equation, you need to run it though parseInt() first. e.g.
var age = parseInt(nameAge.value, 10);
Or if you want to use decimal values (floats) you need to run it through parseFloat()
var salary = parseFloat(nameSalary.value);
Passing the radix (10) as the second parameter to parseInt() will prevent older browsers which use ECMAScript less than version 5 from interpreting numbers starting with a 0 as octal values.

Parse your input to an int (or a float if you want decimals!), it's reading as a string, thus concatenating.
var salary = parseInt(nameSalary.value);
var age = parseInt(nameAge.value);

To get a numeric from a form field, you have to get it converted to a number, the quickest way to do that is to subtract zero from that variable.
salary-=0;
increase_1=salary+((salary*10)/100);
salary_2=salary+increase_1;
Your salary of "1000" will result in an (int)1000 that is then *10 = 10000 then /100 = 100 and added to the original sum of 1000 to make 1100.
You could try using a function or a prototype to do the leg work for you,
Number.prototype.percent = function(p){
return ((this-0)*p)/100;
}
then you can simply... increase_1=salary+(salary.percent(10));

Related

jQuery Conditional Decimal Greater Than Comparison

I have an odd issue that I'm not sure quite how to fix, but here it goes.
I've got a return from an AJAX query and this is how two parts are returned (and how they look in the preview panel):
id:1
paid: "158.40"
balance: "79.20"
So initially I had just tried the following (after noticing an issue):
if(item.balance > item.paid){
var test = "balance greater than paid";
}else{
var test = "balance is not";
}
But in the above case, it returns the first test meaning that somewhere, the it thinks that 79.20 is greater than 158.40, which is obviously not what I want.
So I tried this:
var paid = parseFloat(item.paid).toFixed(2);
var balance = parseFloat(item.balance).toFixed(2);
And just switch the first line of the above conditional statement to if(balance > paid) and it still did the same thing...
So I am at a loss, if anyone can help - I'd be very appreciative.
Don't use toFixed when comparing those values, because it just gives you another string, which it can't compare numerically in the way you're trying to compare. Just compare the outputs of parseFloat.
var paid = "158.40";
var balance = "79.20";
$(".string").text(paid > balance);
paid = parseFloat("158.40");
balance = parseFloat("79.20");
$(".float").text(paid > balance);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
String compare:
<span class="string">
</span>
</div>
<div>
Float compare:
<span class="float">
</span>
</div>
try to use Number() to convert string to numbers first
if(Number(item.balance) > Number(item.paid)){
var test = "balance greater than paid";
}else{
var test = "balance is not";
}
Use it like below
var paid = parseFloat(item.paid);
var balance = parseFloat(item.balance);
Then compare it will take you into right condition
Above you are using toFixed which again returns string.
Referring to toFixed method, it is returning a String, not a Number. Hence the comparison result is not expected. There is no need to call this method for your case. If you have concern on the precision, take a look on this question
var item = {
id: 1,
paid: "158.40",
balance: "79.20"
};
var paid = parseFloat(item.paid);
var balance = parseFloat(item.balance);
console.log("paid=" + paid);
console.log("balance=" + balance);
console.log("paid>balance=" + (paid > balance));

Javascript Floating Number Comparison

I'm trying to do what I thought was pretty straight forward but having odd results. I have two fields on a page: transactionAmount and transactionLimit. When the button is clicked, it calls a javascript function that makes sure the amount isn't greater than the limit:
var transactionAmount = parseFloat(document.getElementById("amount").value).toFixed(2);
var transactionLimit = parseFloat(document.getElementById("limit").value).toFixed(2);
if (transactionAmount > transactionLimit) {
alert("Over limit");
}
If I set the transactionAmount to be $2.00 and the transaction Limit to be $100.00, I get the over limit alert. If I set the transactionAmount to be $1.00 then it works fine. Basically any other value less than $1.00 works if the limit is $100.00 but anything over $1.00 gives me the error.
Would be grateful for some insight! Thank you!
The main problem happening because of toFixed(2) it converts your result to string that's why your condition is not working as you expected. just wrap it with preceding + character to make it Number from String
var transactionAmount = +(parseFloat('2.00').toFixed(2));
var transactionLimit = +(parseFloat('100.00').toFixed(2));
console.log(transactionAmount,transactionLimit, typeof transactionAmount,typeof transactionLimit )
if (transactionAmount > transactionAmount ) {
console.log("Over limit");
}
Try to add the function "Number()" to you values, toFixed() actually transform them to string. You can also add a "+" before to do the same action.
Example:
var transactionAmount = Number(parseFloat("150.00").toFixed(2)); //or: +parseFloat("150.00").toFixed(2)
var transactionLimit = Number(parseFloat("100.0").toFixed(2)); //or: +parseFloat("100.0").toFixed(2)
if (transactionAmount > transactionLimit)
{
alert("Over limit");
} else {
alert("you ok dude");
}
Output:
"Over limit"
I hope it helps you!

JavaScript parseFloat() issue

Okay so my code works fine but when a decimal i.e. 60.1, 60.2, 60.3, etc. is input for #chance it screws up profit and pay.
For example: 60% is input for chance, 1 for bet. It returns 1.65 for pay and 0.65 for profit. That's all correct.
But when I put 60.1, it returns 16.5 ( wrong decimal ) and 15.5 for profit. 16.5 seems like an easy fix but Idk how to fix it, but I have no idea why it's returning 15.5 for profit and thought maybe if I fixed pay it would fix the issue with profit.
What's wrong?
Thanks.
<script>
$(document).ready(function(){
function updateValues() {
// Grab all the value just incase they're needed.
var chance = $('#chance').val();
var bet = $('#bet').val();
var pay = $('#pay').val();
var profit = $('#profit').val();
// Calculate the new payout.
var remainder = 101 - chance;
pay = Math.floor((992/parseFloat((chance+0.5))) *100)/100;
// Calculate the new profit.
profit = bet*pay-bet;
profit = profit.toFixed(6);
// Set the new input values.
$('#chance').val(chance);
$('#bet').val(bet);
$('#pay').val(pay);
$('#profit').val(profit);
}
parseInt($('#chance').keyup(updateValues));
parseInt($('#bet').keyup(updateValues));
parseInt($('#pay').keyup(updateValues));
parseInt($('#profit').keyup(updateValues));
});
</script>
parseFloat((chance+0.5))
looks very wrong. chance is a string, so the + operator will perform string concatenation. When you input 60, it becomes
parseFloat("60"+0.5) === 600.5
while when you input 60.1 it is
parseFloat("60.1"+0.5) === 60.1
You probably wanted
(992/(parseFloat(chance)+0.5))*100
// or
(992/parseFloat(chance)+0.5)*100
// or
992/parseFloat(chance)*100+0.5
// or something along these lines
Change parseFloat((chance+0.5)) into (parseFloat(chance)+0.5).
Actually, I can't see why it's working with 60, either. chance, as a value of a text field, is a string: "60". Strings don't add, they concatenate: "60" + 0.5 is "600.5", same as "60" + "0.5".
Try something like this:
$(document).ready(function(){
function updateValues(){
var chance = $('#chance').val();
var bet = $('#bet').val();
var pay = $('#pay').val();
var profit = $('#profit').val();
pay = ((992/Math.floor(+chance+0.5))/10).toFixed(2);
profit = (bet*pay-bet).toFixed(6);
$('#chance').val(chance);
$('#bet').val(bet);
$('#pay').val(pay);
$('#profit').val(profit);
}
$('#chance').keyup(updateValues);
$('#bet').keyup(updateValues);
$('#pay').keyup(updateValues);
$('#profit').keyup(updateValues);
});
Something is wrong with your Math.
Note:
You don't have to use parseInt() or parseFloat() to make Strings to Numbers. the + symbol in front of your String that is a Number will convert it to a Number.
See http://jsfiddle.net/PHPglue/JQJMD/ for more details.

Adding a 0 before decimal entered in input?

I'm attempting to finish up a quick form using jQuery that needs to add a 0 before a decimal point if the decimal is the first char entered in the input.
For example,
.25 would become 0.25 before the form is submitted.
However, 2.05 would stay as 2.05, and no 0 would be added.
Is there a simple function here that could help me out? I'd rather not write something long and detailed if it's not necessary.
Also, here is the input box that I am asking for help with, for reference
<input type="number" name="dailygain" id="dailygain" />
You can use parseFloat function to format float numbers.
var el = document.getElementById("dailygain");
el.value = parseFloat(el.value);
Multiply by 1 (*1) to make it numeric.
If you make it a number, it'll do it for you automatically; formatting based on your systems locale.
Example:
var x = '.25';
console.log( x*1 ); // 0.25
The same can be accomplished with a unary plus (e.g., console.log( +x ); )
Put this in a function run onsubmit.
var num=$("#dailygain").val(); //read the number from the textbox
num=num.toString(); //convert that number to a string
if (num.charAt(0)==".") //check if the string starts with a period
num="0"+num; //if so, add a 0 in front of it
$("#dailygain").val(num); //write the number back to the tb
parseFloat is probably more suited, but anyway :
$('#dailygain').on('keyup', function() {
if (this.value[0] === '.') this.value = '0'+this.value;
});
FIDDLE
​
$("input[name=dailygain]").keyup(function(){
var val = this.value;
if(val.charAt(0) === '.'){
this.value = ('0'+val);
}
});
http://jsbin.com/ofivun/2/edit

length does not work after multiplication

Edit: Solution: http://jsfiddle.net/VnXtP/
Why dosent this work?
http://jsfiddle.net/uc7kT/
<input type="text" name="item_quantity" id="item_quantity" value="1" />
<input type="text" name="item_price" id="item_price" value="24998" hidden="hidden" />
$('#item_quantity').change(function() {
var quantity = $('#item_quantity').val();
var price = $('#item_price').val();
var total = quantity * price;
alert(total.length);
});
Length is defined for strings, not numbers. If you wish to do this as a mathematical operation, you must convert the input strings to numbers first. If you actually want the length of the number string (I don't know why you would), you need to convert the number to a string first:
$('#item_quantity').change(function() {
var quantity = parseInt($('#item_quantity').val(), 10);
var price = parseFloat($('#item_price').val());
var total = quantity * price;
alert(total.toString().length);
});
Use:
alert(total);
Instead of:
alert(total.length);
You may also want to consider converting the values of the input to a float, or integer value before performing the math.
http://jsfiddle.net/samliew/uc7kT/5/
total is a number. It does not have the property "length".
Try
alert(total);
I guess that is what you want.
In javascript a number is a number and a string is a string.
What can be sometimes confusing is that a number can automagically become a string when that is needed (for example adding a string to it).
Numbers do not have a length property, strings instead do. Also in javascript when you ask an object for a property that is not present normally you just get the undefined value.
var quantity = $('#item_quantity').val();
var price = $('#item_price').val();
item_quantity and item_price are text inputs, and you need to change it to Integer before you multiply. use parseInt() to do it.
var quantity = parseInt($('#item_quantity').val(),10);
var price = parseInt($('#item_price').val(),10);
and use alert(total); not alert(total.length);

Categories

Resources