What is wrong with my simple math equation - javascript

I am trying to create a simple calculator that will return the amount of sales tax plus the amount after tax. If I input $80 and the sales tax is 7.5% I should get back an amount of $86 but instead I am getting $806 returned to me. I am unsure why.
//calculation
var total = (itemCost + (itemCost * salesTax/100));
total = Math.round(total)

you need var total = (parseInt(itemCost) + (parseInt(itemCost) * salesTax/100));

The thing is that when you retrieve the value, it is a string. Parse it as a number value by doing:
var salesTax = Number(document.getElementById("salesTax").value);

When you are getting the values of the text fields you have strings. Javascript does a lot of type inferring, that's why it almost works. Your expression gets translated to:
(String)"80" + ((String)"80"*(int)0.075)
(String)"80" + (int)6
And now the String operator+(String, Any) is called which is defined as string concatenation. Therefore you end up with "80" + "6" => "806".
If you for example would write:
"80" * "1" + "80" * "7.5"/"100" you would indeed get the expected result of 86.
But to be sure everything works as expected you should indeed parse the values from a string value to a number value (with parseInt resp. parseFloat).

Related

jQuery object - Value = value + number - Doesn't work?

I'm attempting to update a value in an object and set it to the current value + another number. So for instance, if an object's value is 5, I want it to update like this: object key : current value (5) + 7
container[response["id"]]["quantity"] += quantity;
console.log(container[response["id"]].attr("quantity"));
This is what I'm currently attempting.. I end up with 57 instead of 12.
Any ideas?
You get as a string and + with strings concatenate them. First parse to the number using parseInt() or parseFloat() than add.
let number = parseInt(container[response["id"]]["quantity"]);
number += quantity;
container[response["id"]]["quantity"] = number;
The issue is, the value return by response["id"]]["quantity"] is a string. And when you try to add a number using + to a string, then it will concatenate it, something like 5 + 7 is 57. To deal with this, you have to parse the number to Int or to Float by using parseInt() or parseFloat(). Ex:
let num = parseInt(container[response["id"]]["quantity"]);
num += quantity;
container[response["id"]]["quantity"] = num;

Aligning Decimal Values with Blank Space String?

I am having trouble adding blank spaces to align the decimals. I understand the logic but I can't put it into code.
for(var j in totals_array)
{
var amount = format_numeric_with_commas(totals_array[j].amount);
var currency = totals_array[j].currency;
if(j < 1)
{
costs_total.push(currency + " " + amount + "\x0A");
}
else
costs_total.push(currency + Array(0).join(" ") + amount + "\x0A");
}
totals_array holds a number of objects which looks like this.
{"currency":"AUD","amount":210543}
format_numeric_with_commas gives me the amount value in the appropriate format which is stored into the variable amount. While currency takes the currency of the value, i.e. GBP, USD, etc. What the if statement is for checks if it's the first index in the array. As I already sort the values with the highest at the top. So what I want is for the other values to align with the top number's decimal.
I take the currency type and value and push into a new array called costs_total. This is what it currently looks like.
Current layout:
How would I go about doing a loop to check how many spaces are needed for different lengths of currency values?
Why not do something like this instead? (some examples with actual text / numbers)
costs_total.push(String.Format("{0} {1,12:N}\x0A", "USD", 123456.0));
// "USD 123,456.00\n"
costs_total.push(String.Format("{0} {1,12:N}\x0A", "AUD", 123.0));
// "AUD 123.00\n"
costs_total.push(String.Format("{0} {1,12:N}\x0A", currency, amount));
You'd just need to find the number of digits in the largest number and set the width (12 in this case) appropriately.

Adding multiple HTML form input values in JavaScript

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.

My result in my jQuery gives NaN

I am getting NaN as result and its beacuse my jquery is multiplying numbers that look like "204,3 * 3"
How can I deal with it?
I cant change the price, so what can I do?
"234 * 2" works fine as soon as the number have ',' I get NaN.
<script type="text/javascript">
$('.quantity').keyup(function () {
var parent = $(this).parent(),
price = parent.find('.price').html(),
quantity = parent.find('.quantity').val(),
result = price * quantity;
parent.find('.price2').html(result);
});
</script>
<span class="price">69,9</span>
<input type="text" class="quantity">
<span class="price2">69,9</span>
<span class="total">Total:</span>
<div class="line2"></div>
Check my JSfiddle everything is there
Any kind of help is appreciated
Javascript uses North American number formatting, which means the , is used as a thousands seperator and the . is used decimal separator.
You have two solutions to your problem:
Teach your users to enter numbers like 1000.25
Write a routine to turn 1.000,25 into 1000.25
String.prototype.replace would be your friend on the second choice.
You are multiplying two strings here and not numbers..
Convert them using parseInt with radix
OR
Convert them using parseFloat
Change this line
result = price * quantity;
TO
result = parseInt(price,10) * parseInt(quantity,10);
OR
result = parseFloat(price) * parseFloat(quantity);
You're trying to multiply strings...use the parseFloat() and a replace() method as shown in your jsFiddle update here
$('.quantity').keyup(function () {
var parent = $(this).parent(),
price = parent.find('.price').html().replace(',', '.'),
quantity = parent.find('.quantity').val().replace(',','.'),
result = parseFloat(price) * parseFloat(quantity);
parent.find('.price2').html(result);
});

Simple math in jquery

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;

Categories