javascript (200-200)/100 = 9009 - javascript

So I am working on a formula with javascript.
and this is the formula. The data for the tank variables is gathered from inputfields.
y = ((tank1 + tank2 + (tank 3 /25)) - (tank4 + tank4))/100;
alert(y);
so for tank1 = 100 tank2 = 100 and tank3 = 0 tank4 = 100 and tank5 =100
according to javascript the answer to this is 9009 while it is supposed to be 0.
for tank1 = 90 tank2 = 90 tank3 = 0 tank4 = 90 and tank5 = 90 answer = 818.6
I tried changing the divisions to multiplications /25 to 0.04 and /100 to 0.01 but the results were the same.
I also tried renaming the tanks in case they were referring to the wrong tanks.
I have also tried alerting the tanks and they gave the right inserted numbers back.
I am running Jquery.
Does anyone Know what is causing this?

Just use parseInt(tankX) for every tank variable and it will work as expected.
This is because your values come from input fields as strings not integers.
Reference: parseInt

Related

How do you round down to one decimal, even if it ends with a 0 in JavaScript?

I have a product page that is fetching products information and displaying the products on the page. The API returns three price points. I have to add them up and display the price rounded down to one decimal. I have a solution already working, but it only works if it's not a whole number.
22.7312 returns 22.7, but 22.0 returns 22. I would like to always show one decimal, even if it's a zero. This is my current solution. How can I change it so that it shows the one decimal, even if it's a zero?
Math.floor(
(parseFloat(product.price1['regionalPrice'])
+ parseFloat(product.price2['marketPrice'])
+ parseFloat(product.price3['localPrice'])
) * 10) / 10
You need to format your float result with the .toFixed(x) method.
Here is a full code sample for this:
const p1 = parseFloat(product.price1['regionalPrice']);
const p2 = parseFloat(product.price2['marketPrice']);
const p3 = parseFloat(product.price3['localPrice']);
const price = Math.floor((p1 + p2 + p3) * 10) / 10;
const displayPrice = price.toFixed(1);
You could try rounding your numbers with the number.toFixed() function where you pass 1 as a function argument.
I tried it and
num = 22; num = nums.toFixed(1); console.log(num)
prints out 22.0.
Hope that this is what you were looking for ^^

Creating a Profit Calculator

I'm trying to create a basic profit calculator but I am struggling with one issue.
I've written some basic javascript and the formula almost works. However my issue is that the decimal point doesn't seem to want to work properly. For example:
What is the case cost: 2.80
How may units per case: 2
What is the sell price: 3.15
Total Profit = 1.75 Profit should of course be, 0.175
I'm a complete newbie to JavaScript so your help would be much appreciated.
<form id="profitCalculator">
<p><label>What is the case cost? <input type="text" name="casecost"></label></p>
<p><label>How many packs / units per case? <input type="text" name="packs"></label></p>
<p><label>What is the sell price? <input type="text" name="sell_price"></label></p>
<p>Total profit £: <input type="text" name="profit"></p>
document.getElementById('profitCalculator').onclick = function () {
var casecost = this.elements['casecost'].value || 0;
var packs = this.elements['packs'].value || 0;
var sell_price = this.elements['sell_price'].value || 0;
var profit = sell_price - casecost / packs;
this.elements['profit'].value = profit.toFixed(2); }
Thanks
It should be
var profit = (sell_price - casecost) / packs;
BUT - Never calculate currency with decimals in Javascript!
Javascript will truncate decimal values when they become to long, possibly resulting in nasty rounding errors. Always multiply your values by 100, then calculate everything, and at last, divide by 100 again.
Look at order of operations, you may know this as 'BODMAS'
Supporting Link: http://www.mathsisfun.com/operation-order-bodmas.html
Change to (sell_price - casecost) / packs;
your problem occurs because operators procedence.
var profit = sell_price - casecost / packs;
/ (division) occurs first than - (minus).
As your example.
2.80 / 2 = 1.4
3.15 - 1.4 = 1.75
You should put some parenthesis covering what has to priority, in your case, to get the value 0.175, you should put the like this.
(3.15 - 2.80) / 2 = 0.175
in code
var profit = (sell_price - casecost) / packs;
See MDN's reference on Operator Precedence and you'll see that division (and multiplication) is done before addition or subtraction. So you have essentially:
3.15 - (2.80 / 2) = 1.75
Instead of:
(3.15 - 2.80) / 2 = 0.175
Also note, as #Adrian Schmidt pointed out, using floating point numbers for math is a bad idea. If you do that above calculation in javascript you actually get:
0.17500000000000004
Because computers don't have infinite precision when representing floating point numbers. See, for example: Is floating point math broken?
So your formula should be:
(sell_price - casecost) / packs
Another thing to consider is that the values you get from your text boxes are strings, not numbers. Your formula works because there is no - operator for strings, so javascript automatically converts your values to numbers. But this is a dangerous thing to rely on. For example, if you did this:
sell_price + casecost
With your example inputs, the result would be:
"3.152.80"
Because it's doing string concatenation, not addition.
So it's worth using parseFloat to convert your strings. (and parseInt for packs as it is, presumably, an integer)
So a complete example might look like this:
var casecost = parseFloat(this.elements['casecost'].value) * 100 || 0;
var packs = parseInt(this.elements['packs'].value, 10) || 0;
var sell_price = parseFloat(this.elements['sell_price'].value) * 100 || 0;
var profit = ((sell_price - casecost) / packs) / 100;
this.elements['profit'].value = profit.toFixed(2);
Also note that if packs is 0, then you'll have a divide by zero error. You'll want to add logic to check the value of packs and do something when it's zero (not calculate the profit).

when generating normally-distributed random values, what is the most efficient way to define the range?

FYI: random == pseudo-random
A. when generating uniformly-random numbers, I can specify a range, i.e.:
(Math.random()-Math.random())*10+5
//generates numbers between -5 and 15
B. generating a set of random values with a version of Gaussian-esque normal randomness:
//pass in the mean and standard deviation
function randomNorm(mean, stdev) {
return Math.round((Math.random()*2-1)+(Math.random()*2-1)+(Math.random()*2-1))*stdev+mean);
}
//using the following values:
{
mean:400,
standard_deviation:1
//results in a range of 397-403, or +-range of 3
},
{
mean:400,
standard_deviation:10
//results in a range of 372-429, or +-range of 30
},
{
mean:400,
standard_deviation:25
//results in a range of 326-471, or +-range of 75
}
each one gives me a range of approximately standard_deviation*(+-3) (assuming I left the program running longer).
C. I can calculate this range as follows:
assuming I want a range from 300-500, so var total_range = 200;
my mean is 400, my +-range is total_range/2 (var r = 100)
so standard_deviation would be r/3 or in this case 33.333.
This seems to be working, but I have no idea what I'm doing with math so I feel like an idiot, this solution feels kludgy and not totally accurate.
My question:
is there some formula that I'm dancing around that can help me here? my requirements are as follows:
must be able to define a range of numbers accurately.
must be done in JavaScript, as efficiently as possible.
I think maybe I'm close but it's not quite there.
Subtracting two random numbers doesn't give you a normal distribution, it will give you numbers that decline linearly on both sides of zero. See the red diagram in this fiddle:
http://jsfiddle.net/Guffa/tvt5K/
To get a good approximation of normal distribution, add six random numbers together. See the green diagram in the fiddle.
So, to get normally distributed random numbers, use:
((Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random()) - 3) / 3
This method is based on the central limit theorem, outlined as the second method here: http://en.wikipedia.org/wiki/Normal_distribution#Generating_values_from_normal_distribution
I wanted to have gaussian random numbers between 0 and 1, and after many tests (thanks to #Guffa answer too) I found this to be the best:
function gaussianRand() {
var rand = 0;
for (var i = 0; i < 6; i += 1) {
rand += Math.random();
}
return rand / 6;
}
And as a bonus:
function gaussianRandom(start, end) {
return Math.floor(start + gaussianRand() * (end - start + 1));
}

Rounding the number within two digits after the comma with javascript

I have a product to add into the store, where there are two input fields priceBase and priceFinal. First is without TAX, second is with TAX.
While using this javascript function:
jQuery(function($){
var priceBase = $('input[name="mprices[basePrice][]"]', '#productPriceBody');
var priceFinal = $('input[name="mprices[salesPrice][]"]', '#productPriceBody');
var priceDiff = priceFinal.val() - priceBase.val();
var priceTax = priceDiff / priceBase.val();
alert(priceFinal.val()); // 1.40004
alert(priceBase.val()); // 1.16667
alert(priceDiff); // 0.23333399999999993
alert(priceTax); // 0.19999999999999993
});
How I suppose to round a priceTax value from 0.19999999999999993 to 0.20 ? Like normal math calculation you know, if it's 4 and below, it rounds to lower, if it's 5 it rounds to higher number.
Thanks for suggestions in advance.
You seem to want
alert(priceDiff.toFixed(2));
But you should parse the values before you do maths. It works here because you're lucky :
"33"-"12" => "21"
"33"+"12" => "3312"
So to avoid bugs in the future (when you use + instead of - for example) I'd suggest to always parse the field values :
var priceDiff = parseFloat(priceFinal.val()) - parseFloat(priceBase.val());

What's wrong with this code to find heightInInches?

After click, a calculated BMI is shown as 0.3; expected answer was 22.8
Code snippet in question:
calculateButton.addEventListener('click', function() {
var feet = feetField.value;
var inches = inchesField.value;
var heightInInches = (feet * 12) + inches;
bmiDisplay.text = ((weightField.value / (heightInInches * heightInInches)) * 703).toFixed(1);
});
heightInInches should equal 68, not 608. Seems like somehow feet (5) is being multiplied by 120 instead of 12 and then tacking on the inches (8) at the end, but I don't quite understand why that's happening, and why it's hiding from me when I step through the code?
Debugger shows the correct values for feet(5) and inches(8) in the formula but an incorrect value assigned to heightInInches after the calculation.
Link to BMI formula
I think I formatted the question correctly; long time listener, first time caller. I've just been staring at it too long... I had screenshots of my UI and the debugger but I had to remove those images from the post. Ok, thanks for checking it out.
inches is a string so when you do the + operator, it concatenates it. You can simply do
var heightInInches = (feet * 12) + inches*1;
and it will treat it as a number.
Try by adding:
var feet = parseFloat(feetField.value);
var inches = parseFloat(inchesField.value);

Categories