JavaScript / jquery Calculations issue - javascript
Hi i have issue with the below JavaScript code not taking current GrossTotal() value until i rewrite Quantity or the UnitPrice values
$(document).ready(function () {
$("[id*=gridpur]input[type=text][id*=txtCalc]").on('keyup', (function (e) {
var unitprice = $(this).closest('tr').find("input[type=text][id*=txtCalcUnitprice]").val();
var quantity = $(e.target).closest('tr').find("input[type=text][id*=txtCalcQuantity]").val();
var total = unitprice * quantity;
var cost = (total / GrossTotal())*100;
$(e.target).closest('tr').find("[id*=lblTotal]").text(total);
$(e.target).closest('tr').find("[id*=lblcost]").text(cost);
}));
});
var gross;
function GrossTotal() {
gross = 0;
$("[id*=gridpur][id*=lblTotal]").each(function (index, item) {
gross = gross + parseInt($(item).text());
});
$("[id*=lblGrandTotal]").text(gross);
return gross;
}
for example if have entered the following values output i get which is not correct
ProductName UnitPrice Quantity Amount Cost %
product1 9 1 9 Infinity
product2 9 1 9 100
product3 9 1 9 50
I only get the correct values after rewriting Quantity or the UnitPrice which is
ProductName UnitPrice Quantity Amount Cost %
product1 9 1 9 33.3
product2 9 1 9 33.3
product3 9 1 9 33.3
Make sure, you default them to 0 when you read the value from the input. Also Check for 0 before dividing it
unitprice = !isNaN(unitprice) ? 0 : unitprice;
quantity = !isNaN(quantity) ? 0 : quantity;
var total = unitprice * quantity;
var grossTotal = GrossTotal(),
cost = 0;
if(grossTotal > 0) {
cost = (total / grossTotal) *100;
}
Also it is a better habit to use radix when using parseInt
parseInt($(item).text(), 10)
The problem is that GrossTotal() adds up the values in all the lblTotal fields, but you're not filling them in until after you call it. Change these lines:
var cost = (total / GrossTotal())*100;
$(e.target).closest('tr').find("[id*=lblTotal]").text(total);
$(e.target).closest('tr').find("[id*=lblcost]").text(cost);
to:
$(e.target).closest('tr').find("[id*=lblTotal]").text(total);
var cost = (total / GrossTotal())*100;
$(e.target).closest('tr').find("[id*=lblcost]").text(cost);
Related
how to get consecutive value of a changing object in javascript
I am New to Programming, and want to write a simple code that will allow me to get consecutive value from a live feed strings from server, where I need help is how to do below task First, let me make an example Like getting a live price update of Dash coin - let's says price is currently #1- $55, then it changes to #2- $56, then it changes to #3- $57, then it changes to #4- $58, then it changes to #5- $54, now it's no longer consecutive The above shows a #4 consecutive increase in Price value My question is How to set this function #how to get changing values when it increases or decreases conservatively a number of times! For instance, if I want to get an alert when the Dash Price increases consecutively #4 times or more in a row or any x number of times Will appreciate a guide on how to go about this in JavaScript. //ok first I tried the above BELOW, but I didn't get the expected results - how I used it below: What did I do wrong? const WebSocket = require('ws'); var ws = new WebSocket('wss://ws.binaryws.com/websockets/v3?app_id=1089'); var lastTick = null; ws.onopen = function(evt) { ws.send(JSON.stringify({ticks:'R_100'})); }; ws.onmessage = function(msg) { var data = JSON.parse(msg.data); var currentTickTime = data.tick.epoch; var currentTick = data.tick.quote; const timerz = 1000; //console.log(currentTick,'\n', balance) var tickTime = new Date(currentTickTime * timerz).toLocaleString(); //testing code below function handleNotification(){ if (balance > 3){ console.log("RISE UP-3times."); // Send notification that price is rising. } if (balance < -3){ console.log("FALL DOWN-3times."); // Send notification that price is falling. } } var currentPrice = 0; var balance = 0; setInterval(async () => { const previousPrice = currentPrice; currentPrice = await currentTick; if (currentPrice > previousPrice){ //console.log('Higher Price') if (balance >= 0) balance++ else balance = 0; }else if (currentPrice < previousPrice){ //console.log('Lower Price') if (balance <= 0) balance-- else balance = 0; }else{ // Price remains unchanged. } handleNotification(); console.log(currentPrice,'\n', balance) }, 2000); lastTick = currentTick; }; I also tried the second option below but, the highest - num_consec value was 1 & -1, even when there are multiple consecutive higher than that. Below is the code used: const WebSocket = require('ws'); var ws = new WebSocket('wss://ws.binaryws.com/websockets/v3?app_id=1089'); //////////////////////////////////////////////////// var lastTick = null; var lastTickTime = null; ws.onopen = function(evt) { ws.send(JSON.stringify({ticks:'R_100'})); }; ws.onmessage = function(msg) { var data = JSON.parse(msg.data); var currentTickTime = data.tick.epoch; var currentTick = data.tick.quote; const timerz = 1000; //console.log(currentTick,'\n', balance) var tickTime = new Date(currentTickTime * timerz).toLocaleString(); //console.log('ticks update: %o', currentTick, '\n', '-----------------------',tickTime); //testing code below //////////////////////////////////////////////////////////////////// var price = lastTick; // or whatever initial value var num_consec = 0; var positive = true; //needs default setInterval(function() { var newprice = currentTick; // code to grab price from source, edit this to grab from your api if (Math.abs(price - newprice) >= 1) { // detect within a certain range, OP specified 1 if (price - newprice > 0 && positive) { // consecutive up num_consec += 1; } else if (price - newprice < 0 && !(positive)) { // consecutive down num_consec += 1; } else if (price - newprice < 0 && positive) { // went down and broke streak num_consec = 0; positive = false; } else if (price - newprice > 0 && !(positive)) { //went up and broke streak num_consec = 0; positive = true; }; price = newprice; //reset price delta console.log("Updated Info:",'\n', price, num_consec)// update price in html or elsewhere, console.log unnecessary if (num_consec > 2) { // do something with consec info console.log((positive) ? `Consecutive ${num_consec} times `+"up" : `Consecutive ${num_consec} times `+"down") }; }; newprice = null; // reset variable }, 1000); // check new price every 1000 ms (1s) //console.log(currentTick,'\n', num_consec) lastTick = currentTick; lastTickTime = tickTime; }; will appreciate all the help I can get- Please kindly help me check the code to know what i did wrong
Quick and easy answer here. function handleNotification(){ if (balance > 3){ // Send notification that price is rising. } if (balance < -3){ // Send notification that price is falling. } } var currentPrice = 0; var balance = 0; setInterval(async () => { const previousPrice = currentPrice; currentPrice = await getDashPrice(); if (currentPrice > previousPrice){ if (balance >= 0) balance++ else balance = 0; }else if (currentPrice < previousPrice){ if (balance <= 0) balance-- else balance = 0; }else{ // Price remains unchanged. } handleNotification(); }, 60000); Nothing complicated. We just track the price. If the price is lower than when we last checked, we decrease the balance value. If it's higher, we increase it. If the balance value is positive and the price decreases, we set it back to 0 because it's no longer consecutive. And then vice versa. Balance simply tracks how many negative or positive consecutive results occurred. This doesn't do much for you if the price change is very small though. You would need to add a threshold to the if statement if you'd like to make it less finely controlled. Edit: Here's how you would do a threshold. var currentPrice = 0; var balance = 0; const threshold = 0.01; // 1% setInterval(async () => { const previousPrice = currentPrice; const currentPriceTemp = await getDashPrice(); if (currentPriceTemp > (previousPrice * (1 + threshold))){ if (balance >= 0) balance++ else balance = 0; currentPrice = currentPriceTemp; }else if (currentPriceTemp < (previousPrice * (1 - threshold))){ if (balance <= 0) balance-- else balance = 0; currentPrice = currentPriceTemp; }else{ // Price remains unchanged. } handleNotification(); }, 60000); That will multiply the previous price by 1.01 or 0.99 depending on if we're testing higher or lower. Basically the price change needs to be more than 1% higher or lower than the previous value. In this example, I also don't set currentPrice if the change didn't meet the 1% criteria. This avoids creeping if the change is less than 1% (e.g. it rises 0.5% 100 times in a row, the consecutive function would never trigger). You can modify threshold variable to whatever you want and the code will only consider it consecutive if the value rises or falls by that percentage. const threshold = 0.01; is 1% and const threshold = 0.99; is 99%.
I would recommend doing this the following way to avoid blocking your thread, but periodically keep checking for a specific range of change. Unfortunately measuring consecutive change is not super simple but can be done with the code below. Possible implementation of setInterval(): var price = 50; // or whatever initial value var num_consec = 0; var positive = true; //needs default setInterval(function() { var newprice = ...; // code to grab price from source, edit this to grab from your api if (Math.abs(price - newprice) >= 1) { // detect within a certain range, OP specified 1 if (price - newprice > 0 && positive) { // consecutive up num_consec += 1; } else if (price - newprice < 0 && !(positive)) { // consecutive down num_consec += 1; } else if (price - newprice < 0 && positive) { // went down and broke streak num_consec = 0; positive = false; } else if (price - newprice > 0 && !(positive)) { //went up and broke streak num_consec = 0; positive = true; }; price = newprice; //reset price delta console.log("Updated Info:", price, num_consec)// update price in html or elsewhere, console.log unnecessary if (num_consec > 2) { // do something with consec info console.log((positive) ? `Consecutive ${num_consec} times `+"up" : `Consecutive ${num_consec} times `+"down") }; }; newprice = null; // reset variable }, 1000); // check new price every 1000 ms (1s) Test Cases (Ouput): Increasing: Test price Value:47 file.html:24 Updated Info: 47 0 file.html:40 Test price Value:46 file.html:24 Updated Info: 46 0 file.html:40 Test price Value:45 file.html:24 Updated Info: 45 1 file.html:40 Test price Value:44 file.html:24 Updated Info: 44 2 file.html:40 Test price Value:43 file.html:24 Updated Info: 43 3 file.html:28 Consecutive 3 times up file.html:40 Test price Value:44 file.html:24 Updated Info: 44 0 file.html:40 Test price Value:43 file.html:24 Updated Info: 43 0 Decreasing: file.html:40 Test price Value:64 file.html:24 Updated Info: 64 0 file.html:40 Test price Value:65 file.html:24 Updated Info: 65 0 file.html:40 Test price Value:66 file.html:24 Updated Info: 66 1 file.html:40 Test price Value:67 file.html:24 Updated Info: 67 2 file.html:40 Test price Value:68 file.html:24 Updated Info: 68 3 file.html:28 Consecutive 3 times down file.html:40 Test price Value:69 file.html:24 Updated Info: 69 4 file.html:28 Consecutive 4 times down file.html:40 Test price Value:70 file.html:24 Updated Info: 70 5 file.html:28 Consecutive 5 times down file.html:40 Test price Value:71 file.html:24 Updated Info: 71 6 file.html:28 Consecutive 6 times down file.html:40 Test price Value:70 file.html:24 Updated Info: 70 0 file.html:40 Test price Value:69 file.html:24 Updated Info: 69 1 If this did not answer your question, or you’d like additional help, please direct message me so we can work through your issue.
Calculating Sales Tax Task Javascript
I'm asked to the following tasks but am having difficulty returning values. Here's the code: function calculateTaxes(price, quantity) { var salesTax = .10; var totalPrice; return totalPrice; } // Test Your Code Here calculateTaxes(1,10); calculateTaxes(1,10) should return a number calculateTaxes(2,5) should return a value of 11 calculateTaxes(5,6) should return a value of 33 calculateTaxes(10,3) should return a value of 33 calculateTaxes(15,12) should return a value of 198 calculateTaxes(25,2) should return a value of 55
It's quite straightforward. price*quantity gives you the total price without tax, and multiplying that with 1 + salesTax gives you the price after tax. function calculateTaxes(price, quantity) { var salesTax = .10; var totalPrice = (price * quantity) * (1 + salesTax); return totalPrice; } console.log(calculateTaxes(1,10)); console.log(calculateTaxes(25,2)); Don't be surprised if you see 55.00000001 instead of 55 though. Do read: Is floating point math broken?
JavaScript Forms - Applying a Discount for a Certain Quantity
I am creating a simple form that calculates price based on quantity ordered and tax. I also want to apply a discount for the following quantities: 10-19: 10% discount 20-29: 20% discount 30-39: 30 % discount 40-99: 40 % discount My issue is that the function still returns the total price without the discount for a certain quantity. When the quantity entered is in a certain range, I have set it up so that the discount updates to the appropriate percentage (var discountPrice). If a discount is applied, then the total should update to the discountedTotal, and calculate the tax and final total from there. However, there seems to be an issue with my syntax since none of this is being applied to the function when I run it. Any insight as to why the if/else statement or the function as a whole is not running properly would be appreciated. If needed, here is the full HTML/JS: http://jsfiddle.net/pas0tmpL/ function priceCalculation() { var nameFirst = document.getElementById("first_name").value; var nameLast = document.getElementById("last_name").value; var phoneNum = document.getElementById("phone_number").value; var quantity = document.getElementById("quantity_order").value; var price = document.getElementById("price_fixed").value; var total = quantity * price; var discountPrice = 0 var discountedTotal = total - (total * discountPrice); const taxRate = 0.085; var tax = total * taxRate; var totalPlusTax = total + tax; if (quantity > 9 || quantity < 20) { discountPrice = .10; total = discountedTotal; } else if (quantity > 19 || quantity < 30) { discountPrice = .20; total = discountedTotal; } else if (quantity > 29 || quantity < 40) { discountPrice = .30; total = discountedTotal; } else if (quantity > 39 || quantity < 100) { discountPrice = .40; total = discountedTotal; } document.getElementById("order_total").value = "$" + totalPlusTax.toFixed(2);
Like this: function priceCalculation() { var nameFirst = document.getElementById("first_name").value; var nameLast = document.getElementById("last_name").value; var phoneNum = document.getElementById("phone_number").value; var quantity = document.getElementById("quantity_order").value; var price = document.getElementById("price_fixed").value; var total = quantity * price; var discountPrice = 0 ; var discountedTotal = 0; const taxRate = 0.085; var tax = total * taxRate; var totalPlusTax = total + tax; if (quantity > 9 || quantity < 20) { discountPrice = .10; total = total - (total * discountPrice); } else if (quantity > 19 || quantity < 30) { discountPrice = .20; total = total - (total * discountPrice); } else if (quantity > 29 || quantity < 40) { discountPrice = .30; total = total - (total * discountPrice); } else if (quantity > 39 || quantity < 100) { discountPrice = .40; total = total - (total * discountPrice); } document.getElementById("order_total").value = "$" + totalPlusTax.toFixed(2); } // end function priceCalculation();
You have several problems that I can see. One is, you calculate the discountedTotal at the beginning using var discountPrice = 0 var discountedTotal = total - (total * discountPrice); total - (total * 0) will just give you total. You should probably only set discountedTotal after you know what your discountPrice is... Your if statements have some problems also. As a hint, || means "or". Thus your first if is saying "if the quantity is more than 9 or less than 20"--and every integer in existence is either more than 9 or less than 20 (some are both!). So you'll only ever attempt to apply the first discount, and that to everything. Good luck!
Javascript random min max doesn't work
I am trying to make a simple program for a tabletop game that calculates damage. So I want to use random between two integers with a couple of percentage stuff to calculate damage. The problem is random doesn't work for me. It doesn't matter what numbers I set as min or max, it always starts from 0 to the number before max. <script> function showDiv() { var armor = document.getElementById('armortype').value; var damage = document.getElementById('dmgtype').value; var min = document.getElementById('mindmg').value; var max = document.getElementById('maxdmg').value; document.getElementById('result').style.display = "block"; for (var i=0;i<100;i++) { var dmg_done = Math.floor(Math.random()*max+min+1); document.getElementById('test').innerHTML += " " + dmg_done; } } </script> So for min = 3, max = 6 I get the following 100 numbers: 3 1 2 2 0 2 2 1 2 2 3 3 4 0 1 1 2 2 5 2 3 5 3 3 3 4 0 0 5 2 3 0 4 0 2 1 0 5 4 1 0 5 5 4 2 1 2 4 5 1 5 1 0 4 3 5 2 1 4 3 1 1 5 1 4 2 1 0 3 3 3 4 3 4 5 4 2 0 2 4 5 0 3 1 2 5 0 1 5 1 2 2 1 4 0 0 0 1 4 2 So it doesn't matter that min is 3, it randomizes from 0 and there is not even a single 6 in the result.
Demo: http://jsfiddle.net/zprr6/ You want to utilize it as such: var dmg_done = Math.floor(Math.random() * (max - min + 1) + min); The reason it starts at 0, is because the Math.random function produces a float from 0-1 (as many JS functions and features do). So, by telling it to start at max - min + 1, ie 4, it avoids using the 0 as a starting value.
Try replacing Math.floor(Math.random()*max+min+1) with Math.floor(Math.random() * (max - min + 1) + min)
So why don't you try calculating random like this function getRandom (min, max) { return Math.random() * (max - min + 1) + min; } Edit: to add to the comment var valOne = $("#input-1").val(), valTwo = $("#input-2").val(); $("#button").click(function() { $("#answer-input").val(getRandom(parseInt(valOne), parseInt(valTwo))); );
Found the problem. both min and max were used as strings, not numbers. So I just parsed them as ints like this: var min = parseInt(document.getElementById('mindmg').value); var max = parseInt(document.getElementById('maxdmg').value); and it works flawlessly now
Try Math.floor((Math.random() * (max+1-min))+min); max+1 - so that the maximum is include, and +min so that the min is respected Test case var max = 6; var min = 3; var result = ""; for(var i=0;i<100;i++) { result += Math.floor((Math.random()*(max+1-min))+min) +","; } console.log(result); results (5 runs) 3,4,5,6,6,4,5,6,3,5,5,3,5,5,6,6,5,4,5,5,4,5,6,6,6,5,6,3,4,3,5,3,6,6,6,3,6,3,5,6,5,4,6,6,6,5,5,4,3,5,6,6,3,6,6,3,6,5,6,5,6,5,3,3,5,6,6,4,5,5,4,3,5,4,4,4,3,5,4,5,5,3,3,4,4,6,3,3,3,4,4,3,6,3,4,4,3,3,4,6, 6,5,4,3,6,4,4,6,4,4,5,5,3,4,6,4,4,3,4,6,6,5,3,6,4,5,4,6,5,4,4,3,5,6,4,3,5,5,3,5,4,3,6,4,3,3,3,4,6,5,6,3,5,5,6,6,6,5,5,6,5,6,5,4,5,4,4,5,3,6,3,3,6,5,6,3,5,3,6,3,5,6,3,4,5,4,3,5,3,5,3,5,3,5,3,5,3,5,5,6, 3,3,6,5,5,3,3,4,3,5,6,4,3,3,6,3,6,6,3,4,5,5,5,4,4,6,6,3,3,3,5,4,4,3,6,6,5,5,5,4,4,4,5,3,6,3,5,4,5,6,3,6,5,3,3,4,5,4,6,3,4,6,3,6,3,4,6,5,3,6,3,5,6,5,6,4,5,4,3,6,4,4,3,4,6,3,5,5,3,6,6,6,5,6,6,4,3,6,3,4, 4,4,3,6,4,6,4,3,5,4,5,3,4,5,6,6,6,3,4,4,4,4,4,4,5,6,4,4,6,6,5,5,5,3,6,3,5,4,6,5,5,4,5,4,5,4,3,3,5,4,6,5,5,4,4,6,6,6,3,4,6,6,3,6,5,5,4,6,6,4,3,4,6,3,5,6,4,3,5,6,3,4,3,6,6,6,6,3,3,4,4,4,6,6,4,3,6,5,4,3, 4,5,3,6,3,4,5,4,4,5,5,3,3,6,6,4,6,4,5,5,3,5,5,5,3,6,3,5,4,5,5,6,6,4,4,5,3,3,4,5,5,5,4,6,5,4,5,4,5,6,6,3,3,3,4,3,4,6,5,3,5,5,3,3,5,6,3,5,6,3,6,3,5,5,5,6,3,6,4,3,4,5,5,3,6,6,6,6,4,5,6,5,3,4,4,3,4,6,3,6, On an additional note, getting the value of a textbox always returns a string, so the following (min and max) are both strings var min = document.getElementById('mindmg').value; var max = document.getElementById('maxdmg').value; I would check that they are actually numbers, and cast them, before using them in the Math, something like var min = +(document.getElementById('mindmg').value); var max = +(document.getElementById('maxdmg').value); putting the + at the front will casue a number cast IF IT CAN, if it can't, it will be NaN (Not a Number), so before you use, check that they are not NaN. Nan can easily be checked, as nothing equala Nan not even Nan so something like if(min === min && max === max) { //... all good to use con.. } will check that they are actually numbers as Nan will never equal NaN but 3 will always equal 3
How do I get cart checkout price exact to the penny using Javascript?
How do I get cart checkout price exact to the penny using Javascript? Right now after taking out all of the trial .rounds etc I was trying.. I am coming up 1.5 cents too high using a high 15 products/prices to test. for (var i = 0; i < Cookie.products.length; i++) { boolActive = Cookie.products[i].og_active; if (boolActive) { itemPrice = Cookie.products[i].price; itemQty = Cookie.products[i].quantity; itemDiscountPercent = Cookie.products[i].discount_percent; subtotal = itemPrice * itemQty; priceDiscount = (subtotal * itemDiscountPercent); discountAmount += priceDiscount; } } if (!isNaN(discountAmount)) { var newCartTotal = (cartTotal - priceDiscount); alert("New Cart Total: " + newCartTotal); }
var newCartTotal = (cartTotal - pricediscount).toFixed(2) that will give you the value, but it will be a string. If you need it to stay numeric, use: var newCartTotal = ((cartTotal - pricediscount * 100) << 0) / 100;
You need to round the discount for each line item: priceDiscount = round_to_hundredth(subtotal * itemDiscountPercent) Note that this result may not agree with the result you'd get if you add the unrounded results and then round the sum. However, this is the way invoices usually work when calculated by hand (especially since each item can have a different discount percent, so the discount is calculated for each line). I think you left out a line saying discountAmount += priceDiscount.
modify your code to : priceDiscount = parseFloat( (subtotal * itemDiscountPercent).toFixed(2) ); and: newCartTotal = parseFloat( (cartTotal - priceDiscount).toFixed(2) );