Not getting the result I expected from this calculation - javascript

I'm using a form to help determine the strength for an action in a game I'm making a plugin for. The player fills in some form fields and selects 1 value from a drop down and then clicks calculate. The result if I use an actual calculator is what I expected but, the result from my javascript function is not. I've been wrestling with it for a while but, can't seem to work out why it's failing to calculate correctly. Below is the function:
function wgtcalc() {
document.wgtcalc.strDSAtk.value =
(document.wgtcalc.strBaseSpeed.value * document.wgtcalc.strAltitude1.value) +
(document.wgtcalc.strBaseSpeed.value * document.wgtcalc.strAltitude2.value) +
(document.wgtcalc.strDistance.value / document.wgtcalc.strFullSwing.value);
}

Try:
function wgtcalc() {
document.wgtcalc.strDSAtk.value =
( Number(document.wgtcalc.strBaseSpeed.value) *
Number (document.wgtcalc.strAltitude1.value)) +
( Number (document.wgtcalc.strBaseSpeed.value) *
Number (document.wgtcalc.strAltitude2.value)) +
( Number (document.wgtcalc.strDistance.value) /
Number (document.wgtcalc.strFullSwing.value) );
}
As pc-shooter pointed out you're doing a calculation on strings.

Related

Receiving NaN when trying to make calculations with 4 Digits Numbers in Javascript

Here is the javascript code for calculating the price of the item the problem is that whenever the price is 4 digits the value that return is NaN.
totalDiv: function() {
var porcentage = +this.vmodel.form.percentage / 100;
this.calculatedTotal = +this.vmodel.form.purchase_price / (1 - porcentage);
this.vmodel.form.sell_price += this.calculatedTotal;
return +this.calculatedTotal.toFixed(2);
},
Anyone could help me to understand what I'm doing wrong?
Thanks.

JavaScript Math Expression Yields Different Results

The following is a line I have in my Javascript code. It outputs -5108024 and some change when sqftVal = 2828 and bathsVal = 3.5.
out.value = -6932000 + 221400 * Math.log(sqftVal) + 637.2*Math.exp(bathsVal) + 51640;
However, when I manually type this in my calculator, I get roughly -5099721 and some change. I get the same result in R. Why does JavaScript mess up the math, and what can I do to fix this?
Calculator/R input:
-6932000 + 221400 * ln(2828) + 637.2 * e^(3.5) + 51640 = -5099721.073
I don't believe this is a floating point error because as I add more terms, the difference becomes fairly large.
Plus, everything was matching up until I added the fourth term (+51640) which made no sense to me.
There must be some other code that is interfering with your values or something, because the code shown does not produce the value you report.
var sqftVal = 2828;
var bathsVal = 3.5;
var value = -6932000 + 221400 * Math.log(sqftVal) + 637.2*Math.exp(bathsVal) + 51640;
console.log(value);

Adding let values together in JavaScript

I'm working on a tax calculator app with JavaScript and have a problem adding let values.
When trying to add 3 different tax values together, in the console, the answer I always get is the first of the values.
let basicRate,
higherRate,
additionalRate;
function calculateTaxDue(grossSalary) {
if (grossSalary > 150000) {
basicRate = parseFloat((46351 - 11000) * 0.2).toFixed(2);
higherRate = parseFloat((150000 - 46351) * 0.4).toFixed(2);
additionalRate = parseFloat((grossSalary - 150000) *
0.45).toFixed(2)
taxDue = parseFloat((basicRate + higherRate +
additionalRate)).toFixed(2);
}
}
calculateTaxDue(150001)
console.log(parseFloat(basicRate).toFixed(2));
console.log(parseFloat(higherRate).toFixed(2));
console.log(parseFloat(additionalRate).toFixed(2));
console.log(parseFloat(basicRate + higherRate +
additionalRate).toFixed(2));
Just prints the first value (basicRate) to the console. I'm confused by this.
Apologies for lack of detail first time around.
Thanks
You are getting this result because basicRate, higherRate and additionalRate are strings.
basicRate + higherRate +
additionalRate produces the string "7070.2041459.600.45" and parseFloat("7070.2041459.600.45").toFixed(2) the returns 7070.20.
Only use .toFixed when you actually want to display numbers:
let basicRate,
higherRate,
additionalRate;
function calculateTaxDue(grossSalary) {
if (grossSalary > 150000) {
basicRate = (46351 - 11000) * 0.2;
higherRate = (150000 - 46351) * 0.4;
additionalRate = (grossSalary - 150000) *
0.45;
taxDue = basicRate + higherRate +
additionalRate;
}
}
calculateTaxDue(150001)
console.log(basicRate.toFixed(2));
console.log(higherRate.toFixed(2));
console.log(additionalRate.toFixed(2));
console.log((basicRate + higherRate +
additionalRate).toFixed(2));
Most importantly: Read the documentation of the functions you are using.
parseFloat expects a string as input and returns a number. There is no point in passing a number to it like you do in parseFloat((46351 - 11000) * 0.2).
.toFixed returns a string. Don't use it if you want to actually perform further computations with the number values.
And finally, don't use floating point values to perform monetary computations. The results will be incorrect due to rounding errors and loss of precision. Express all numbers as integers.

jquery: percentage of two numbers (Part 2)

this is continuation of last successful topic
jquery: percentage of two numbers
First of all I want to thank you for your prompt support of previuous post.
Now I would like to make my script a little bit more complicated. I want to achive the following: If I insert PRICE1 and PRICE2 to have RATE between THEM, then I can change the RATE with other value and PRICE2 to change to the corespondent value according to RATE value.
My script of calculation is close to be correct, but my low knowledge about JQuery make me to ask you where I do something wrong.
Thank you for your support!
<script src="libs/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#PRICE1, #PRICE2").change(function() {
var result = parseFloat(parseFloat($("#PRICE1").val(), 10) - parseFloat($("#PRICE1").val(), 10))/ parseFloat($("#PRICE2").val(), 10) * 100;
$('#RATE').val(result||'');
})
else {
$("#PRICE1, #RATE").change(function() {
var result = parseFloat(parseFloat($("#PRICE1").val(), 10) * parseFloat($("#RATE").val(), 10))/ 100 + parseFloat($("#PRICE1").val(), 10);
$('#PRICE2').val(result||'');
})}
});
</script>
EDITED:
THE CODE ALMOST WORKING CORRECTLY WHICH MIGHT HELP OTHERS:
$(document).ready(function(){
$("#priceOne, #priceTwo").change(function() {
var priceOne = parseFloat($("#priceOne").val());
var priceTwo = parseFloat($("#priceTwo").val());
$('#Rate').val((priceTwo - priceOne) / priceOne * 100); // Set the rate
});
// If price one or the rate is changed, adjust price two.
$("#priceOne, #RATE").change(function() {
var priceOne = parseFloat($("#priceOne").val());
var rate = parseFloat($("#Rate").val());
$('#priceTwo').val((priceOne * rate)/ 100 + priceOne);
});
})
Thank you everyone who help me!!!
There is a else and no matching if. I'm not sure what you're trying to achieve, but some condition needs to be checked.
I'm going to try and code what it appears you need. But I'm going to rename your variables, not only because allcaps are hard to type, but unless it's a constant or a macro, they shouldn't be used.
// In ready() callback
// #NOTE - This does NO error checking for division by 0 or other NaN operations.
// If price two is changed, adjust the rate.
$("#priceTwo").change(function() {
var priceOne = parseFloat($("#priceOne").val());
var priceTwo = parseFloat($(this).val());
$("#rate").val(priceTwo / priceOne); // Set the rate
});
// If price one or the rate is changed, adjust price two.
$("#rate #priceOne").change(function() {
var priceOne = parseFloat($("#priceOne").val());
var rate = parseFloat($("#rate").val());
$("#priceTwo").val(priceOne * rate);
});
There are a few things about your code that needs attention:
parseFloat doesn't take a radix argument, the 10 you pass it is ignored.
parseFloat(parseFloat(... is pointless, I'm not sure why you've done this.
Don't use jQuery to select the same element multiple times in the same scope. Save the value and re-use it - save yourself some cycles.
As I mentioned, don't name your variables in all capitals unless they are some sort of constant that should never be changed, it's good to have clean style habits.

JavaScript function to add two numbers is not working right

My code in HTML takes a user input number in, and it does a calculation and then displays the output. The user chosen input is put into a formula and the result of the formula is added to the user input number, but when it adds the two number together it's adding a decimal spot.
For example, if the number 11 is chosen, the result of Rchange is 0.22, so .22 is then added 11 to be 11.22 for newResistance, but instead it is displaying the value as 110.22 instead.
function calc(form) {
if (isNaN(form.resistance.value)) {
alert("Error in input");
return false;
}
if (form.resistance.value.length > 32) {
alert("Error in input");
return false;
}
var Rchange = .01 * 2 * form.resistance.value;
var newResistance = (form.resistance.value + Rchange);
document.getElementById("newResistance").innerHTML = chopTo4(newResistance);
}
function chopTo4(raw) {
strRaw = raw.toString();
if (strRaw.length - strRaw.indexOf("0") > 4) strRaw = strRaw.substring(0, strRaw.indexOf("0") + 5);
return strRaw;
}
HTML DOM element properties are always strings. You need to convert them to numbers in your usage.
parseInt(form.resistance.value);
parseFloat(form.resistance.value);
+form.resistance.value;
(Any of the three will work; I prefer the first two (use parseInt unless you're looking for a float).)
Try newResistance = +form.resistance.value + Rchange;. This will convert it to a number.
It's because it's treating the values as a string.
form.resistance.value + Rchange are both strings, so it's appending it.
Use the parseInt JavaScript method to get the decimal version.

Categories

Resources