Javascript Investment Calculator [duplicate] - javascript

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 6 months ago.
i need help with a javascript code that's calculate the profit of investment with a rate of 4% daily for a period of 30 days :
Screenshot 1
var minimumAmount = 5;
function DoCalculate() {
var temp1 = $("#txtAmount").val(),
rate = 0.0;
if (!$("#txtAmount").val()) temp1 = 0;
var initial = parseFloat(temp1);
if (initial < minimumAmount) rate = 0;
else rate = 0.04;
var totalReturn = parseFloat(initial * rate * 30);
if (initial < minimumAmount) {
$("#lblDailyProfit").html("0.00");
$("#lblHourlyProfit").html("0.00");
$("#lblTotalProfit").html("0.00");
$("#lblTotalReturn").html("0.00");
} else {
$("#lblDailyProfit").html(parseFloat(initial * rate * 24).toFixed(2));
$("#lblHourlyProfit").html(parseFloat(initial * rate).toFixed(2));
$("#lblTotalReturn").html(totalReturn.toFixed(2));
$("#lblTotalProfit").html((totalReturn - initial).toFixed(2));
}
}
$(function() {
DoCalculate();
$("#txtAmount").blur(function() {
if (parseFloat($(this).val()) < minimumAmount) $("#txtAmount").val(minimumAmount);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I want to add multiple rates like :
if ( initial >= 3000 && initial <= 4900 ) rate = 0.02;
if ( initial >= 5000 && initial <= 49999 ) rate = 0.04;
if ( initial >= 50000 && initial <= 49999 ) rate = 0.09;
I've tried many times but with not results,
I will be happy if someone helps me;
Thanks in advance.

temp = (amount, days)=>{
return amount*1.04**days;
}

Related

Save sum in variable in jQuery each for range

I am working on a specific calculator and I need to sum up variables in my jQuery.each for a range from 0 to 4 (= 5 years).
I have found many pages where the solution is described, but only with references to an element, not to the range.
My code:
jQuery.each(new Array(duration),
function(n){
var investment = 1000; // 1000$
var duration = 5; // 5 years
var revenueRatio = 10; // 10% revenue / year
var reinvest = 50; // 50% reinvestment
if(n == 0){
var revenueReinvest = 0;
var newInvestment = investment;
}else{
console.log(revenueReinvest); // undefined
console.log(newInvestment); // undefined
var interest = ( ( newInvestment - investment ) * ( revenueRatio / 100 ) );
var removeInterest = interest * reinvest / 100;
var restIntereset = interest - removeInterest;
revenueReinvest += restIntereset;
newInvestment = newInvestment + revenueReinvest;
}
}
);
Any help or idea would be great! Thank you!
The issue with the code is that you have declared revenueReinvest and newInvestment inside the if block and using it inside the else block. This wont be possible. Declare revenueReinvest and newInvestment outside each loop and assign the values to them inside if statement. Now you can access the assigned values inside else statement.
You have to declare the variable outside the loop to prevent redeclaring of the variable inside the loop. Each time the variable gets redeclared inside the loop, old value will be lost.
The below code will work
$(document).ready(function () {
const duration = 4;
// Declare here
var revenueReinvest;
var newInvestment;
jQuery.each(new Array(duration),
function (n) {
var investment = 1000; // 1000$
var duration = 5; // 5 years
var revenueRatio = 10; // 10% revenue / year
var reinvest = 50; // 50% reinvestment
if (n == 0) {
// assign value here
revenueReinvest = 0;
newInvestment = investment;
} else {
var interest = ((newInvestment - investment) * (revenueRatio / 100));
var removeInterest = interest * reinvest / 100;
var restIntereset = interest - removeInterest;
revenueReinvest += restIntereset;
newInvestment = newInvestment + revenueReinvest;
}
}
);
console.log(revenueReinvest); // will be defined
console.log(newInvestment); // will be defined
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

snail in the well javascript challenge

This is my first question on stack overflow although this question had been answered before I didn't get enough details to understand why the code was written that way and I didn't just want to copy and paste the solution without understanding it.
The snail climbs 7 feet each day and slips back 2 feet each night, How many days will it take the snail to get out of a well with the given depth?
Sample Input
31
Sample Output
6
this is was what i wrote but it didn't work
function main() {
var depth = parseInt(readLine(), 10);
//your code goes here
let climb = 0, days = 0;
for(climb + 7; climb < depth; days++){
climb += 2;
console.log(days);
try this:
var depth = parseInt(readline(), 10);
var day = 0;
for(let climb = 0; climb <= depth;) {
day +=1;
climb += 7;
if(climb >= depth) {
break;
}
climb -= 2;
}
console.log(day);
Just take input and write this
var day= Math.ceil((depth-2)/5);
and output that!
/* day --> 7++
night --> 2-- */
var day = 0;
var total = 0;
var input = 41;
while (input>total){
day++;
total+=7;
if (total>=input){
console.log(day);
break;
}
total = total -2
}
As mentioned in the comments, no need to loop. Just work out the math of the problem an use that.
function snailCalc (depth, dailyGain, nightlyLoss) {
var days = 1;
var netGain = dailyGain-nightlyLoss;
if(depth > dailyGain ) {
//Basic calc based on net gain taking the first day into account
days = (depth-dailyGain)/netGain;
//Add the fist day
days += 1;
//We want whole days so use Mathc.ceil
days = Math.ceil(days)
//Or we could do all that in one line
//days = Math.ceil(((depth-dailyGain)/netGain) + 1);
}
return days;
}
const gain = 7;
const loss = 2
for(var d = 1; d < 31; d++)
{
console.log(`Depth: ${d}, Days: ${snailCalc(d, gain, loss)}` )
}
Bob
function main() {
var depth = parseInt(readLine(), 10);
console.log(Math.round(depth / 5))
}
function main() {
var depth = parseInt(readLine(), 10);
//your code goes here
var days=1;
var level =0;
for(level =0;level<depth;days++){
level+=7
if(level<depth){
level-=2;
} else{
break ;
}
}console.log(days)
}
Try this, I had the same trouble a couple days ago and we find the error is that using js you need to reset the variable where you sum the result before evaluate again if the distance the snail climbed that day is greater than the depth to end the clycle.
depth = 31;
let days = 0;
let climb = 0;
while(climb < depth){
let result = climb + 7;
if(result >= depth){
days++;
break;
}
climb = result - 2;
days++;
//console.log("climb ",climb);
}
console.log(days);
You can change the function input and test the snipet:
for more you can run code and check result ↗
Eg : main(128) // 26
function main(input) {
let depth = input
let climbsUp = 7
let slipsBack = 2
let distance = climbsUp - slipsBack
let days = 0;
let rDepth = Math.round(depth / distance)
for (let i = 0; i < rDepth; i++) {
distance = distance + 5
days = ++days
if (days === 6) {
console.log('days will it take the snail to get out of a well : ' + rDepth)
} else {
console.log('days will it take the snail to get out of a well : ' + rDepth)
break;
}
}
}
main(42);
main(128);

JS math causing total sum to be negative

I am trying to develop a game.
However my math is a problem. Every time the total profit value goes into negative value.
How can i fix it?
var gameProfit = 10000;
var tinyOwned = 0;
var tinyCost = 10000;
var tinyIncome = 0;
function buyTiny(){
if (gameProfit >= tinyCost){
tinyOwned += 1;
document.getElementById('tiny-owned').innerHTML = tinyOwned;
document.getElementById('current-profit').innerHTML = "Profit : $ " + (gameProfit -= tinyCost * tinyOwned);
document.getElementById('tiny-cost').innerHTML = "Next Cost : $ " + (tinyCost * tinyOwned + 10000);
document.getElementById('tiny-income').innerHTML = "Income : $ " + (tinyIncome = 15000 * tinyOwned);
}
}
var timer = 0;
var timeInterval = 10;
window.setInterval(function gameTimer() {
if (timer >= 0) {
timer++;
document.getElementById('timer-value').style.width = timer + "px";
}
if (timer >= 600) {
timer = 0 + 1;
document.getElementById('timer-value').style.width = "0px";
tinyIncome = 15000 * tinyOwned;
gameProfit += tinyIncome;
document.getElementById('current-profit').innerHTML = "Profit : $ " + (gameProfit);
}
}, timeInterval);
Can anyone see the problem in my code? gameProfit Variable goes into negative how to fix this?
You allow someone to buy when: gameProfit >= tinyCost
But you reduce gameProfit like: gameProfit -= tinyCost * tinyOwned
So you take more then you initially check! to fix:
if (gameProfit >= tinyCost * tinyOwned){
The math looks really messy especially since it is mixed up with setting InnerHtml. I strongly advice to first do the math and then update the Html.InnerHTML
Offtopic: make sure you escape your data if you are ever going to make it to a multiplayer game, else people can crosside script it (Can I escape html special chars in javascript?) but this is something you don't really have to worry about at this stage.

Creating a slider between two numbers

So I've been working on re-producing the slider found here https://www.skylight.io/ ( Scroll down to find the price slider ).
So far Ive managed to create something similiar, but some numbers are hard coded, making it difficult to change and not very re-usable.
I've been researching around and I think I need to use Math.log() and Math.exp() together to achieve something like in the link above but I'm not sure.
Heres a jsfiddle of what I have so far https://jsfiddle.net/7wrvpb34/.
I feel that its the maths part of this problem that is halting me I think, so any help would be greatly appreciated.
Javascript code below:
var slider = document.getElementById("slider")
var sliderFill = document.getElementById("slider-fill")
var knob = document.getElementById("knob")
var mouseDown;
var mousePos = {x:0};
var knobPosition;
var minPrice = 20;
var price = 0;
var minRequests = 50;
var requests = 50 + ",000";
var incrementSpeed = 2;
var incrementModifier = 20;
var incrementValue = 1;
var minMillionCount = 1;
var millionCount = 1;
var previousRequestAmount = 0;
document.getElementById("price").innerHTML = price;
document.getElementById("requests").innerHTML = requests;
highlightTable(1);
document.addEventListener('mousemove', function(e) {
if(mouseDown) {
updateSlider(e);
}
})
function updateSlider(event) {
mousePos.x = event.clientX - slider.getBoundingClientRect().left;
mousePos.x -= knob.offsetWidth / 2;
console.log(mousePos.x);
if(mousePos.x < 0) {
knob.style.left = "0px";
sliderFill.style.width = "0px";
price = 0;
requests = 50 + ",000";
document.getElementById("price").innerHTML = price;
document.getElementById("requests").innerHTML = requests;
return
}
if(mousePos.x > slider.offsetWidth - 20) {
return
}
sliderFill.style.width = mousePos.x + 10 + "px";
knob.style.left = mousePos.x + "px";
//Increase requests by using X position of mouse
incrementSpeed = mousePos.x / incrementModifier;
requests = minRequests + (mousePos.x * incrementSpeed);
//Round to nearest 1
requests = Math.round(requests / incrementValue) * incrementValue;
if (requests >= 1000){
var m = requests/ 1000;
m = Math.round(m / 1) * 1;
//Problem, lower the modifier depending on requests
incrementModifier = 20 * 0.95;
document.getElementById("requests").innerHTML = m + " million";
//Adjust Prices
if(( requests >= 1000) && (requests < 10000)) {
var numOfMillions = requests / 100;
//Round to closest 10.
//10 * number of millions
var rounded = Math.round(numOfMillions / 10) * 10;
price = minPrice + rounded;
highlightTable(3);
}
//Adjust Prices
if(requests >= 10000) {
var numOfMillions = requests / 1000;
var rounded = Math.round(numOfMillions / 1) * 1;
var basePrice = minPrice * 6;
price = basePrice + rounded;
highlightTable(4);
}
} else {
incrementModifier = 20;
document.getElementById("requests").innerHTML = requests + ",000"
if(requests < 100) {
highlightTable(1);
price = 0;
} else {
highlightTable(2);
price = 20;
}
}
previousRequestAmount = requests;
document.getElementById("price").innerHTML = price;
}
knob.addEventListener('mousedown', function() {
mouseDown = true;
});
document.addEventListener('mouseup', function() {
mouseDown = false;
});
function highlightTable(rowNum) {
var table = document.getElementById("payment-table")
for(var i = 0; i < table.rows.length; ++i) {
var row = table.rows[i]
if(i == rowNum) {
row.style.background = "grey"
} else {
row.style.background = "white";
}
}
}
Thank you for your time.
If you want it to be reusable you need to create a mathematical function that assigns a result to the number of requests. I will give you a very easy example.
If you want a different result for 1,10,100,100,10000 etc
var d = Math.log10(requests);
if(d<1){
doSomething();
}else if(d<2){
doSomethingElse();
} //etc
This way if you want to change the specific values that create certain results, all you need to do is change the function.
This only works if your tiers of requests follow a math function, if they don't you need to hard code it.
However if say they don't follow a math function, but you know how you would like them to change based on a value then you can do this.
var changingValue = 4;
if(requests < 400*changingValue){
doSomthing();
}else if(requests <= 400*changingValue*changingValue){
doSomethingElse();
}else{// the requests is greater than any of the above
doTheOtherThing();
}
Edit:
For the second one you need to make sure that each condition if always larger than the other from top to bottom.
The description "increasingly increasing" matches an arbitrary number of functions. I assume you also want it to be continuous, since you already have a non-continuous solution.
TL;DR
Use an exponential function.
Generic approach
Assuming imin and imax are the minimal and maximal values of the slider (i for input) and omin and omax are the minimal and maximal values to be displayed, the simplest thing I can think of would be a multiplication by something based on the input value:
f(x)
{
return omin + (omax - omin) * g((x - imin) / (imax - imin));
}
This will pass 0 to g if x == imin and 1 if x == imax.
The return value r of g(y) should be
r == 0 for y == 0
r == 1 for y == 1
0 < r < y for 0 < y < 1
The simplest function that I can think of that fulfills this is an exponential function with exponent > 1.
An exponent of 1 would be a linear function.
An exponent of 2 would be make the middle of the slider display one fourth of the maximum price instead of half of it.
But you really need to find that exponent yourself, based on your needs.

Calculating investment values with javascript

I am currently learning javascript. I have created a calculator to find invesment future value. It is giving me an incorrect value when it displays the future value. I have checked the formula several times but it still gives me an error. Also, I have set alerts to appear if the interest is less than 0 or greater than 20 but nothing is showing. How would i be able to properly display the correct future value and alerts when necessary? Example
Javascript
var $ = function (id) {
return document.getElementById(id);
}
var calculate_click = function () {
var investment = parseFloat( $("investment").value );
var annualRate = parseFloat( $("rate").value ) /100;
var years = parseInt( $("years").value );
$("futureValue").value = "";
if (isNaN(investment) || investment <= 0) {
alert("Investment must be a valid number\nand greater than zero.");
} else if(isNaN(annualRate) || annualRate <= 0 || annualRate > 20) {
alert("Annual rate must be a valid number\nand less than or equal to 20.");
} else if(isNaN(years) || years <= 0 || years > 50) {
alert("Years must be a valid number\nand less than or equal to 50.");
} else {
//var monthlyRate = annualRate / 12;
//var months = years * 12;
var futureValue = 0;
for ( i = 1; i <= years; i++ ) {
futureValue = ( futureValue + investment ) *
( 1 + annualRate );
}
$("futureValue").value = futureValue.toFixed(2);
}
}
var clear_click = function () {
$("investment").value = "";
$("rate").value = "";
$("years").value = "";
$("futureValue").value = "";
}
window.onload = function () {
$("calculate").onclick = calculate_click;
$("investment").focus();
$("clear").onclick = clear_click;
}
Using .value is incorrect, its javascript, while this is jquery, try adding a # in front and use .val() instead.
Its similar to this:
jquery function val() is not equivalent to "$(this).value="?
EDIT
He's not using jquery, ignore this.
If I remember the future value correctly, you are messing up the formula, which is why you aren't getting the expected value.
Change:
for ( i = 1; i <= years; i++ ) {
futureValue = ( futureValue + investment ) *
( 1 + annualRate );
}
To:
futureValue = investment*Math.pow((1+annualRate), years);
Not quite sure why you are looping through each year, but it should be based on powers to the number of years (again, if I remember correctly)
// to calculate the increase in production for each month
function getPlan(startProduction, numberOfMonths, percent) { // the function is declared
let Goals = []; //Goals is assigned
let currentProduction=startProduction; //declaring the currentProduction by assigning the value of startProduction
for(let i=0; i<numberOfMonths;i++){ //for each month, increase the currentProduction by the percentage interest = Math.floor(currentProduction+(currentProduction*(percent/100)));
currentProduction= interest;
//after each iteration, assign the new currentProduction
Goals.push(Math.floor(currentProduction));
//adding the currentprodcution of each months to the Goals
} return Goals; } console.log(getPlan(2000,6,67));
Output:
[ 3340, 5577, 9313, 15552, 25971, 43371 ]

Categories

Resources