I am bewildered as to why I cannot add three numbers together. Here is my HTML:
<div><label>Sales Price: </label>
<input type="number" name="sales_price" value="3">
</div>
<div><label>Incentives: </label>
<input type="number" name="incentives" value="2">
</div>
<div><label>Acquisition Fee: </label>
<input type="number" name="acq_fee" value="1">
Here is my JavaScript:
var salesPrice = document.getElementsByName("sales_price")[0];
var incentives = document.getElementsByName("incentives")[0];
var acqFee = document.getElementsByName("acq_fee")[0];
var netCapCost = salesPrice.value - incentives.value + acqFee.value;
I wanted a simple calculation to be done: (3-2+1) = 2. However, netCapCost returns 11, which is the concatenation of the result of (3-2) and 1. What did I do wrong? Many Thanks in advance!
You need to convert those values into numbers with parseInt() or else the + operator will be interpreted as string concatenation. You are doing
var netCapCost = salesPrice.value - incentives.value + acqFee.value;
Which is
var netCapCost = "3" - "2" + "1"
"3"-"2" will return 1, which is what you want but 1 + "1" will be concatenated into "11" since the right operand is a string. So Number + String -> concatenation
var salesPrice;
var incentives;
var acqFee;
var npc;
function calculate(e) {
var netCapCost = (parseFloat(salesPrice.value) - parseFloat(incentives.value) + parseFloat(acqFee.value)).toPrecision(3);
npc.value = netCapCost;
}
window.onload = function (){
salesPrice = document.getElementsByName("sales_price")[0];
incentives = document.getElementsByName("incentives")[0];
acqFee = document.getElementsByName("acq_fee")[0];
npc = document.getElementsByName("npc")[0];
salesPrice.onchange = calculate;
calculate();
};
Your problem is that text fields value is always of type STRING. When subtracting it forces a conversion to type FLOAT. Then the plus operation shares an opperator with the concatenate operation. So when you have two strings being added it concatenates rather than converting to FLOAT or INT. So basically you have "2"-"1" being converted to 2-1 as strings cannot be subtracted which gives you (1) then you have (1)+"1" which will concatenate rather than add as you have a string. Always use parseFloat or parseInt when expecting numeric data from user entry as it will always be a string when originally submitted.
you are doing a string concatation, all value get from input value are string,
the first calcuation salesPrice.value - incentives.value is currect is becuase, the - sign convert the incentives.value to number
the currect way is
var netCapCost = parseInt(salesPrice.value, 10) - parseInt(incentives.value, 10) + parseInt(acqFee.value, 10);
it's better to use a Math library to do the calcuation in javascript, because sooner or later, you will encounter the problem like 0.3 - 0.2 = 0.09999999
I think confusion here is HTML 5 introduces input type number however javascript engine doesn't introduce support for reading such specific fields. We end up using old traditional way of reading input field value which defaults everything to string.
Only advantage of using number type field would be that you do not have to worry about exception/erroneous situation where number is not being entered.
Other answer suggesting to use parseInt function, is the way to go unless you have luxury of introducing javascript framework like jQuery and use more sophisticated approach for reading it.
Related
I have just started learning Javascript. I am doing the course in Viope World. I need to get two different numbers, but each time, I get the same number for the num and exponent variables, while the function calcPower is correct. I don't understand how to get different inputs in the function fetchValue() without having HTML for this task. I have tried using the method Document.querySelector() and other things which shouldn't be complicated for such an exercise.
These are the requirements:
Fill in the missing functions fetchValue(id) and calcPower(base, exponent). The function fetchValue(id) looks for a HTML text input element and returns its value. The function calcPower(base, exponent) has to calculate and return a number based on the values passed to it. Note that all of the printing happens within the pre-made section of the program.
This is the part of the code I can't change:
function calcFunc(){
var num = fetchValue("num");
var exponent = fetchValue("exponent");
console.log("The number " + num + "to the power of " + exponent + " is:");
console.log(calcPower(num, exponent));
}
My code:
function fetchValue(id){
let val = document.querySelector("input").value;
return val;
}
function calcPower(base, exponent){
var result = 1;
for(var counter=0; counter<exponent;counter++){
result*=base;
}
return result;
}
querySelector returns a reference to the first element of the given selector. See https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector. It is not the obvious way to fetch your values given that your function is set up to handle element ids.
Instead, individual elements with unique id can be referenced using document.getElementById("elementID") and you want the .value property of the element. See https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById.
To input values, the html needs some sort of input, you could use text or number inputs (both return strings, but the number input restricts entries to digits). The markup for these would be something like:
Number: <input type="number" id="inputValue"></input><br>
Exponent: <input type="number" id="inputExponent"></input>
Note the use of ids as attributes of the elements.
Javascript is a loosely typed language, meaning strict definition of variable types is not needed. This means that JS can make sensible calculations from 2*2 or "2"*"2" (both are calculated to be 4). However, it is good practice to formally convert string digits to numbers when you intend using them for calculations (not least because JS interprets "2"+"2" as "22" because + is both an arithmetic addition operator and a string concatenation operator so if you give it strings, JS assumes you want to concatenate them).
So, the fetchValue function could include the use of parseInt(string) to convert the input string values to numbers.
These principles are combined in the following working snippet to illustrate the approach:
function calcFunc(){
let num = fetchValue("inputValue");
let exponent = fetchValue("inputExponent");
console.log("The number " + num + " to the power of " + exponent + " is:");
console.log(calcPower(num, exponent));
}
function fetchValue(id){
return parseInt(document.getElementById(id).value);
}
function calcPower(base, exponent){
let result = 1;
for(let counter=0; counter<exponent;counter++){
result*=base;
}
return result;
}
input {
width: 3em;
}
Number: <input type="number" id="inputValue"></input><br>
Exponent: <input type="number" id="inputExponent"></input>
<p>
<button onclick="calcFunc()">process</button>
I hope this helps, If the exponent is negative, the result is 1 / (base^exponent). For example: 2^(-4) = 1 / (2^4) = 1 / 2 / 2 / 2 / 2. meaning the number 2 to the power of -4 is: 0.0625 and not 1
Math.abs is important here...
function fetchValue(id){
return document.getElementById(id).value;
}
function calcPower(base, exponent){
if (exponent == 0){
return 1;
}
else if(exponent < 0){
exponent = Math.abs(exponent);
return (1 / calcPower(base, exponent));
}
else if(exponent > 0){
return base * (calcPower(base,exponent - 1));
}
};
I can't seem to figure out why the subtraction is working in my code, but when I change the subtraction sign to an addition sign, I get a console error: Uncaught TypeError: undefined is not a function. Where is the error?
Here is a fiddle with the subtraction: http://jsfiddle.net/c8q7p6ac/
Here is a fiddle with the addition in place of the subtraction sign: http://jsfiddle.net/c8q7p6ac/1/
The subtraction sign and the addition sign are in the variable updatedNumber
HTML:
<div class="amount">$1000.00</div>
<input class="new-number" type="text">
<div class="button">Click</div>
jQuery:
$('.button').on('click', function(){
//get value of input
var newNumber = $('.new-number').val();
//get total number value
var totalNumber = $('.amount').text();
var getNumberOnly = totalNumber.indexOf('$') + 1;
var newTotalNumb = totalNumber.substr(getNumberOnly, totalNumber.length);
//add new number to total number
var updatedNumber = (newTotalNumb + newNumber).toFixed(2);
//and update total
$('.amount').html('$'+updatedNumber);
});
The subtraction works because JavaScript converts them to numbers. However, in case of addition, it converts them to strings as soon as one of the operands is a string.
You need to convert the string to a number:
var updatedNumber = (parseInt(newTotalNumb) + parseInt(newNumber)).toFixed(2);
While dealing with decimal points, you can also use parseFloat which will preserve the decimal points.
Here's the updated fiddle.
$("#next").click(function() {
var text = $("#textbox").val();
var Numbers = text.substring(4, 8); //To get the 4 numbers
var Num = parseInt(Numbers, 10); //To convert to an integer?
var Add = +(Num).val() + 1; //Increment 1?
$("#textbox").val(Add); //Output final value
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="next" value="Increment" />
<br/>
<input type="text" id="textbox" value="ABC-123" />
I have a text box with a string of "ABC-1234" as the value and a button. I'm trying to add 1 to what's entered in the text box every time I click the button. I'm fairly new to programming but this is what I've come up with, which ends with the result of NaN.
The problem you want to solve is to add one to the numeric part of a mixed alpha-then-numeric text string.
Assuming your text will contain an alpha part, then a literal dash -, and finally a numeric part, it is easy to extract the numeric part using the String.split() method.
var text = $("#textbox").val();
var parts = text.split('-');
Now parts[0] is everything to the left of the dash and parts[1] is everything to the right. Just parse that into a number, add one, and add it back with the rest of the text, placing it back in the field.
$("#next").click(function() {
var text = $("#textbox").val();
var parts = text.split('-'); // Get the numbers in parts[1]
var num = parseInt(parts[1], 10); // Convert to an integer
num++; //Increment 1?
$("#textbox").val(parts[0] + '-' + num); //Output final value
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="next" value="Increment" />
<br/>
<input type="text" id="textbox" value="ABC-123" />
This is more flexible than text.substring(4, 8); because it will work with any length string and any length number, as long as there is a dash between them.
your code is almost right, but you have to change a few things to make it "right":
in dependency of the naming convention of javascript write the variables in lower(Camel)Case.
parseInt returns a primitive type of number. There is need for calling val() method on it! There is no function like that. Just use the variable itself
you have to prepend your increased number with the letters you chop of at the beginning.
All in all:
$("#next").click(function(){
var text = $("#textbox").val();
var numbers = text.substring(4); //To get all the numbers
var num = parseInt(numbers, 10); //To convert to an integer?
num = num + 1; //Increment 1?
$("#textbox").val(text.substring(0,4)+num); //Output final value
});
On Load I got my input value 5.02, now i need to change in 6.
Now i am getting either null or 5.02.
How i can get my data is 6???
My code is:::
<input type="number" id="rate" class="form-control rate " th:value="${abc.rate}" placeholder="Rate" />
javaScript:::
$(".rate input[type='number']").change(function() {
$("#rate").val(""); //i am reseting the value
rateForA =$('#rate').val(); //but i am getting null
console.log(rateForA);
});
I think this will help you
$('.rate').change(function(){
var Num = parseFloat($(this).val());
console.log(Math.ceil(Num));
});
Try
$("#rate ").change(function() { //target input via ID
//we don't want to reset, we want to change value
var myNumber = parseFloat($('#rate').val()); //get decimal value
var result = myNumber + 0.98; //Add numbers together
//Or, you can round up to the nearest whole number instead of adding the numbers together
//Thanks to #Bilbo Baggins for this method
//var result = Math.ceil(myNumber);
console.log(result); //result should be 6
});
When you use .val, it's returning the value as a string instead of a number(integer) like this: "5.02"
We need it as an integer like so: 5.02 (no quotes)
So, we must then use parseFloat() (since you're using decimal places in your value) to get the value as an integer instead of a string.
We then either add the numbers together or you can remove the addition line and use the round up method instead to get to 6.
I am reading a select form value and multiplying it by 50 in jquery. I need to add a value of 1 to the qty that is returned by the select menu every time before multiplying by 50. How would I do that? The offending code looks like this.
$('#selectform').val() *50);
If I use
$('#selectform').val() +1 *50);
The result is not correct.
Parentheses should be used.
($('#selectform').val()*1 + 1) *50;
Your current expression is interpreted as:
var something = $('#selectform').val();
var another = 1 * 50;
var result = something + another
The *1 after .val() is used to convert the string value to a number. If it's omitted, the expression will be interpreted as:
var something = $('#selectform').val() + "1"; //String operation
var result = something * 50; // something is converted to a number, and
// multiplied by 50
Correct parentheses and use parseInt function -
(parseInt($('#selectform').val(),10) +1) *50;
The data from $('#selectform').val() is probably being treated as a string.
Use parseInt($('#selectform').val()) to convert it to an int before the multiply.
You should have a look at the operator precedence in JavaScript.
You need to force the addition to happen before the multiplication with parentheses:
bar myVal = ($("#selectform").val() + 1) * 50;