Okay so i asked this question yesterday and revised it based on the direction i was pointed. It works the way i want it when there are items in the list but, when there is 0 it evals to false so the or kicks in no mater what. I don't want that i need it to show 0.00 when the item count is at 0. I know that 0=false that's why or kicks in. Any help/workaround?
var dropResult;
$(function (){
$(".t").click(function(){
dropResult = $("input[name=drop]:checked").val();
dropCalculate();
});
});
function dropCalculate() {
var pricesObj = {
'0':0,
'1':450
};
var dropAmount = $(".itemadd", "#items").length;
$("#dropAmount").html("Total: " + dropAmount);
if (dropResult == 1) {
dropTotal = (pricesObj[dropAmount] * dropAmount) || 450 + (150 * dropAmount - 150);
$("#dropPrice").html("Price Total: $" + dropTotal.toFixed(2));
}else {
dropTotal = (pricesObj[dropAmount] * dropAmount / 2) || 225 + (75 * dropAmount - 75);
$("#dropPrice").html("Price Total: $" + dropTotal.toFixed(2));
}
}
You might get a better response over at the Code Review Stack Exchange on questions where you don't have an immediate problem, but feel that you could improve your code design.
The following code should do the same thing as the code in your example, but I think it's more readable. An object doesn't seem to be necessary for this use case, but may be useful in the future.
Again, I applied the DRY Principle, and this time I removed Magic Numbers(numbers in the code with no immediately clear meaning).
var dropResult;
$(function (){
$(".t").click(function(){
dropResult = $("input[name=drop]:checked").val();
dropCalculate(450);
});
});
function dropCalculate(fullPrice) {
var halfPrice = fullPrice / 2,
quarterPrice = halfPrice / 2,
dropAmount = $(".itemadd", "#items").length,
finalPrice = 0.00;
if(dropAmount > 0){
if (dropResult === 1) {
finalPrice = fullPrice; //the rest of this line was not necessary, as dropAmount - 1 is always 0 here.
} else {
finalPrice = halfPrice + (quarterPrice * (dropAmount - 1));
}
}
$("#dropAmount").html("Total: " + dropAmount);
$("#dropPrice").html("Price Total: $" + finalPrice.toFixed(2));
}
I solved my problem this way. I didn't want to go this route because i felt there was a simpler way.
var dropResult;
$(function (){
$(".t").click(function(){
dropResult = $("input[name=drop]:checked").val();
dropCalculate();
});
});
function dropCalculate() {
var dropAmount = $(".itemadd", "#items").length;
$("#dropAmount").html("Total: " + dropAmount);
if (dropResult == 1 && dropAmount > 0) {
dropTotal = 450 + (150 * (dropAmount -1));
$("#dropPrice").html("Price Total: $" + dropTotal.toFixed(2));
}else if (dropAmount > 0) {
dropTotal = 225 + (75 * (dropAmount -1));
$("#dropPrice").html("Price Total: $" + dropTotal.toFixed(2));
}else {
$("#dropPrice").html("Price Total: $" + (0.00).toFixed(2));
}
}
Related
Trying to calculate Break Even Point (BEP) using jquery:
function roundToTwo(num) {
return +(Math.round(num * 100) / 100);
}
var text = ""
var quantity = 1;
var buy = 0;
var sell = 10;
var bep_pnl = -0.5;
if (buy == 0) {
buy = roundToTwo(sell - 0.01);
while (bep_pnl < 0.01) {
total_amnt_trade = roundToTwo((quantity * buy) + (quantity * sell));
var brokerage_amnt_buy = ((buy * quantity) * 0.08) / 100;
if (brokerage_amnt_buy >= 25) {
var brokerage_buy = 25;
} else {
var brokerage_buy = brokerage_amnt_buy;
}
var brokerage_amnt_sell = ((sell * quantity) * 0.08) / 100;
if (brokerage_amnt_sell >= 25) {
var brokerage_sell = 25;
} else {
var brokerage_sell = brokerage_amnt_sell;
}
var brokerage = roundToTwo(brokerage_buy + brokerage_sell); //brokerage
var transaction_charges = roundToTwo((((buy * quantity) + (sell * quantity)) * 0.00325) / 100); //Transaction Charges
var gst = roundToTwo((((transaction_charges * 18) / 100) + (brokerage * 18) / 100)); //GST
var total_charges = roundToTwo(brokerage + transaction_charges + gst);
bep_pnl = roundToTwo(((sell - buy) * quantity) - total_charges);
text += "<br />New Buy " + buy + " and profit " + bep_pnl;
buy = roundToTwo(buy - 0.01);
}
var bep = roundToTwo(sell - buy);
$('#demo').text(bep);
document.getElementById("testing").innerHTML = text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p id="demo"></p>
<h1 id="testing"></h1>
While running the above codes the result of BEP is 0.04. But it should be 0.
I think it's a technical problem (maybe in while loop) as the formula is correct. (Can be cross-checked in <h1>
It's that extra buy = roundToTwo(buy - 0.01); before the while loop expires that's giving the .04 result. You need to decrement buy at the beginning of the loop, not the end. Set buy = sell before it enters the while, then move buy = roundToTwo(buy - 0.01); to the beginning of the loop.
That would give .03 as the result of var bep = roundToTwo(sell - buy);, which is consistent with the output New Buy 9.97 and profit 0.01.
I have this investment calculator in javascript/jquery. It calculates the profit someone would have, based on specific plans. It's written to work with bitcoin values, which goes like this 0.36000000 BTC. I just need to parse it to 3,6 format.
https://pastebin.com/DZvWxEkt
jQuery(function($){
//Setting calculator
var percent = [0.36,0.46,0.52];
var minMoney = [0.001,5.001, 10.001];
var maxMoney = [5,10,99999999.9999];
$("#btc_amt").val(minMoney[0]);
/*calculator*/
function calc(){
money = parseFloat($("#btc_amt").val());
id = -1;
var length = percent.length;
var i = 0;
do {
if(minMoney[i] <= money && money <= maxMoney[i]){
id = i;
i = i + length;
}
i++
}
while(i < length)
if(id != -1){
profitHourly = money / 100 * percent[id];
profitHourly = profitHourly.toFixed(8);
profitDaily = profitHourly * 24;
profitDaily = profitDaily.toFixed(8);
profitWeekly = profitDaily * 7;
profitWeekly = profitWeekly.toFixed(8);
profitMonthly = profitDaily * 30;
profitMonthly = profitMonthly.toFixed(8);
if(money < minMoney[id] || isNaN(money) == true){
$("#profitHourly").text("Error!");
$("#profitDaily").text("Error!");
$("#profitWeekly").text("Error!");
$("#profitMonthly").text("Error!");
//$("#total_profit").text("Error!");
} else {
$("#profitHourly").text(profitHourly + " BTC");
$("#profitDaily").text(profitDaily + " BTC");
$("#profitWeekly").text(profitWeekly + " BTC");
$("#profitMonthly").text(profitMonthly + " BTC");
//$("#total_profit").text(profitTotal + " BTC");
}
} else {
$("#profitHourly").text("Error!");
$("#profitDaily").text("Error!");
$("#profitWeekly").text("Error!");
$("#profitMonthly").text("Error!");
//$("#total_profit").text("Error!");
}
if(money >= 0.001 && money <= 5 ){
$('#active-plan').text('0.36% Hourly profit');
$("#h_id1").prop("checked", true);
}
if(money >= 5.001 && money <= 10 ){
$('#active-plan').text('0.46% Hourly profit');
$("#h_id2").prop("checked", true);
}
if(money >= 10.001 ){
$('#active-plan').text('0.52% Hourly profit');
$("#h_id3").prop("checked", true);
}
}
calc();
if($("#btc_amt").length){
calc();
}
$("#btc_amt").keyup(function(){
calc();
});
$("#h_id1").change(function(){
if ($(this).is(':checked')){
$('#btc_amt').val('0.001');
}
calc();
});
$("#h_id2").change(function(){
if ($(this).is(':checked')){
$('#btc_amt').val('5.001');
}
calc();
});
$("#h_id3").change(function(){
if ($(this).is(':checked')){
$('#btc_amt').val('10.001');
}
calc();
});
var clipboard = new Clipboard('.btn');
});
Got it working, thank you. Just changed the number of toFixed(n)
$.getJSON( "https://api.coindesk.com/v1/bpi/currentprice/usd.json",
function( data) {
var amountInBtc = 0.005; //convert 0.005 btc to usd
var exchangeRate = parseInt(data.bpi.USD.rate_float);
var amount = amountInBtc * exchangeRate;
console.log(amount);
});
Read the full post here
I'm creating a tug of war website as a small project. My problem is that my javascript doesn't seem to want to work.
<script>
function randomTeam(){
var TeamV = Math.floor((Math.random() *2 ) + 1)
document.getElementById("TeamHeader").innerHTML = "Team: " + TeamV;
return TeamV;
}
function changeWidth(TeamV){
var MetreLeftV = document.getElementById('MetreLeft');
var MetreRightV = document.getElementById('MetreRight');
if(TeamV == 1){
MetreLeftV.style.width += '10px';
MetreRightV.style.width -= '10px';
}
else if(TeamV == 2){
MetreRightV.style.width += '10px';
MetreLeftV.style.width -= '10px';
}
}
</script>
Basically, when the page is loaded the randomTeam function is called, and when the button is pressed, it increments the size of your teams side, and decrements the side of the enemy's team. The problem is, it doesn't work at all. Could anyone help me see where this is going wrong? Thank you in advance :')
You can not just add 10px to the width. Convert the width to a number, add 10, than add px to it.
MetreLeftV.style.width = (parseFloat(MetreLeftV.style.width) + 10) + "px"
Do the same for the others and you will need a check for negative numbers.
function randomTeam() {
var TeamV = Math.floor((Math.random() * 2) + 1)
document.getElementById("TeamHeader").innerHTML = "Team: " + TeamV;
return TeamV;
}
function changeWidth(TeamV) {
var MetreLeftV = document.getElementById('MetreLeft');
var MetreRightV = document.getElementById('MetreRight');
console.log(parseFloat(MetreLeftV.style.width) + 10 + 'px')
if (TeamV == 1) {
MetreLeftV.style.width = parseFloat(MetreLeftV.style.width) + 10 + 'px';
MetreRightV.style.width = parseFloat(MetreRightV.style.width) - 10 + 'px';
} else if (TeamV == 2) {
MetreLeftV.style.width = parseFloat(MetreLeftV.style.width) - 10 + 'px';
MetreRightV.style.width = parseFloat(MetreRightV.style.width) + 10 + 'px'
}
}
window.setInterval( function () {
var move = randomTeam();
changeWidth(move);
}, 1000);
#MetreLeft {
background-color: red
}
#MetreRight {
background-color: yellow
}
<div id="TeamHeader"></div>
<div id="MetreLeft" style="width:200px">Left</div>
<div id="MetreRight" style="width:200px">Right</div>
I'm developing a text-based game, and I have a function (turn()) that determines the user's action based on what button they press.
But every time you press one of the 3 buttons, the console says TypeError: number is not a function.
I've tried many operations (such as moving all of my scripts into one file, defining the game's variable globally, and changing the order of the functions), but it still doesn't work!
Any help?
JavaScript code:
console.log("Resetting resources...");
var turn = 1;
var player = {
damage: Math.floor(Math.random() * 4 + 2), //Deals 2 to 5 damage
healing: Math.floor(Math.random() * 4 + 3), //Heals 3 to 6 health
health: null,
maxHP: 25, //Maximum health (not recommended to change)
special: true,
alive: true
};
var dragon = {
damage: Math.floor(Math.random() * 6 + 1), //Deals 1 to 6 damage
health: null,
maxHP: 28, //Maximum health (not recommended to change)
alive: true
};
player.health = player.maxHP;
dragon.health = dragon.maxHP;
console.log("Resources ready!");
function turn() {
if (player.alive) {
/*Player turn*/
console.log("---------------TURN " + turn + " : PLAYER---------------");
alert("The dragon is still alive!");
console.log("Player HP: " + player.health + "/" + player.maxHP);
switch (action) {
case '1':
console.log("Dealt " + player.damage + " damage!");
dragon.health -= player.damage;
if (dragon.health <= 0) {
alert("The dragon has been slain!");
console.log("---------------DRAGON SLAIN---------------");
dragon.alive = false;
player.alive = false;
}
break;
case '2':
console.log("Recovered " + player.healing + " health!");
player.health += player.healing;
break;
case '3':
alert("Scared of dying, you ditch the scene before you become human toast.");
console.log("---------------PLAYER SURRENDERS---------------");
player.alive = false;
break;
default:
console.error("Random error occured.");
break;
}
/*Reset RNG*/
player.damage = Math.floor(Math.random() * 4 + 2);
player.healing = Math.floor(Math.random() * 4 + 3);
/*Dragon turn*/
console.log("---------------TURN " + turn + " : DRAGON---------------");
console.log("Dragon HP: " + dragon.health + "/" + dragon.maxHP);
console.log("Dealt " + dragon.damage + " damage!");
player.health -= dragon.damage;
if (player.health <= 0) {
alert("You have died!");
console.log("---------------PLAYER DIES---------------");
player.alive = false;
}
/*Reset RNG*/
dragon.damage = Math.floor(Math.random() * 6 + 1);
turn++;
} else if (!player.alive && dragon.alive) {
alert("You have died!\nGAME OVER\nReset the game to play again.");
} else if (!dragon.alive) {
alert("You have slain the dragon!\nGAME OVER\nReset the game to play again.");
}
}
function attack() {
turn('1'); //Error occurs here
}
function heal() {
turn('2'); //and here
}
function flee() {
turn('3'); // and here
}
<button onclick="attack()">Attack</button>
<button onclick="heal()">Heal</button>
<button onclick="flee()">Flee!</button>
You are defining turn to be a variable at the beginning of the script: var turn = 1;.
Then you are trying to redefine it later as a function: function turn() { ... }.
The "problem" is that JavaScript put function definition at the beginning of the block, after variable definition but prior to variable assignment, so in reality your JavaScript code will be interpreted as:
var turn;
function turn() { ... }
turn = 1;
The end result is in fact that turn is a number (1) and this is not a function, so you can't call it with turn('1').
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I'm trying to build a electrical units calculator. I have developed one but I am not satisfied with my code. I am here to ask you guys is there any other way to develop this calculator.
Following is my code :
HTML
<input name="" type="text" value="" onblur="check()" id="bill" />
SCRIPT
<script>
function check()
{
var a=0,b=0,c=0;
var tot = 0;
var tot1=0;
var tot2=0;
var tot3=0;
var a = document.getElementById('bill').value;
if(a>200)
{
b = a - 200;
alert('b is: '+b);
if(b>200)
{
c= b-200;
alert('c is: '+c);
tot1 = 200*4;
tot2 = 200*5;
tot3 = c*6;
tot = tot1 + tot2 + tot3;
alert(tot);
}
else
{
tot1 = 200*4;
tot2 = b*5;
tot3 = c*6;
tot = tot1 + tot2 + tot3;
alert(tot);
}
}
else
{
tot = a*4;
alert(tot);
}
}
</script>
Please help me friends..:)
<script>
function check()
{
var a=0,b=0,c=0;
var tot = 0;
var tot1=0;
var tot2=0;
var tot3=0;
var a = parseFloat(document.getElementById('bill').value);
if(a>200)
{
tot1 = 200*4;
b = a - 200;
alert('b is: '+b);
if(b>200)
{
c= b-200;
alert('c is: '+c);
tot2 = 200*5;
tot3 = c*6;
tot = tot1 + tot2 + tot3;
alert(tot);
}
else
{
tot1 = 200*4;
tot2 = b*5;
tot3 = c*6;
tot = tot1 + tot2 + tot3;
alert(tot);
}
}
else
{
tot = a*4;
alert(tot);
}
}
</script>
<input name="" type="text" value="" onblur="check()" id="bill" />
I think this will do :)
Your code needs to be separated - as well comments are useful to help others understand the purpose of your code. Here's a working example of one:
function check()
{ var initialRate = 4; // electricity charged at this rate below 200
var standardRate = 5; // amount of electricity between 200 and 400 charged at this rate
var overageRate = 6; // the part of electricity usage over 400 at this rate
var electricityUsage = +document.getElementById('bill').value; // convert String to Number
if (isFinite(electricityUsage) || electricityUsage < 0) {
alert('The number entered was invalid, or was less than 0.');
return;
}
// calculates the total
alert(
electricityUsage > 400
? initialRate * 200 + standardRate * 200 + overageRate * (electricityUsage - 400)
: electricityUsage > 200
? initialRate * 200 + standardRate * (electricityUsage - 200)
: initialRate * electricityUsage
);
}
Try this:
function check()
{
// Algorithm
// Slabs : 200 | 400 | ...
// Amoun : 4 | 5 | 6
slabs = [200, 400]
rate = [4, 5, 6]
var total = document.getElementById('bill').value;
// Over the head
if (total > slabs[1]) {
amount = slabs[0] * rate[0] + (slabs[1] - slabs[0]) * rate[1] + (total - slabs[1]) * rate[2];
} else if (total > slabs[0]) {
amount = slabs[0] * rate[0] + (total - slabs[0]) * rate[1];
} else {
amount = total * rate[0];
}
alert("Total charge: " + amount);
}
I think I have it at last. There are three charge-bands and you need to know what portion of a value is in each band. Then you need to apply appropriate multipliers to the amount in each band.
If I'm right, then the code is painfully simple :
function check() {
var a = Number(document.getElementById('bill').value);
var n = 200;
var tot1 = Math.min(n, a);
a = a - n;
var tot2 = Math.max(0, Math.min(n, a));
a = a - n;
var tot3 = Math.max(0, a);
return tot1 * 4 + tot2 * 5 + tot3 * 6;
}
If there were more bands then we would do the calcs in a loop but for three bands this is adequate.
Note: The function returns the calculated total.
See this: Sample
function check()
{
var tot = 0,tot1=0,tot2=0,tot3=0;
var a = document.getElementById('bill').value;
tot1 = (a<=200) ? (a * 4) : 800;
tot2 = (a<=400) ? ((a-200) * 5): 1000;
tot3 = (a-400) > 0 ? ((a-400) * 6): 0;
tot = tot1 + tot2 + tot3;
var msg = "Total Charge: "+tot+"\n Details\n < 200 : "+tot1;
msg += (tot2 != 0) ? "\n200 to 400 : "+tot2 : "";
msg += (tot3 != 0) ? "\n>400 : "+ tot3 : "";
alert(msg);
}