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.
Related
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 have created this function for a shopping basket. To be simple, i have x products with (2 checkbox + quantity input) for each.
The first checkbox add +3, second +8, to the product price. It's like (3+8+price)*quantity. At the end of the page, i have the total result (like product1 + product2...Etc)
The problem is: If i'm posting the form with new quantities, and going back to the page, i have the default result (total price) (of course, checkbox are checked + new quantity with PHP).
Here is my function:
$(function(){
var item_prices = 0;
var total_item_prices = 0;
var total_unique_item_prices = 0;
var total_price = 0;
$.each($('*[data-item-price]'), function(index, element) {
var item_price = $(element).data("item-price");
total_unique_item_prices = parseInt($('[data-total]').html()) + item_price;
total_price = total_unique_item_prices;
$('[data-total]').html(total_unique_item_prices);
})
$.each($('*[data-item-price]'), function(index, element) {
var item_price = $(element).data("item-price");
var price_of_options = 0;
var quantity = parseInt($(element).find('input[data-quantity]').val());
$.each($(element).children().find("[data-price]"), function(index, element2) {
$(element2).click(function(){
var actual_price = parseInt($('[data-total]').html());
var actual_item_price = parseInt($(element).find('[data-item-total]').html());
var price = $(element2).data("price");
if ($(element2).is(':checkbox') && $(element2).is(':checked')) {
price_of_options += price;
$(element).find('[data-item-total]').html(actual_item_price + (price * quantity));
$('[data-total]').html(actual_price + (price * quantity));
}
else {
price_of_options -= price;
$(element).find('[data-item-total]').html(actual_item_price - (price));
$('[data-total]').html(actual_price - (price * quantity));
}
})
})
$(element).find('input[data-quantity]').bind('keyup mouseup', function () {
var new_quantity = parseInt($(element).find('input[data-quantity]').val());
var quantity_dif = new_quantity - quantity;
var actual_price = parseInt($('[data-total]').html());
if (quantity_dif > 0) {
quantity_dif = new_quantity - quantity;
$(element).find('[data-item-total]').html((item_price + price_of_options) * new_quantity);
$('[data-total]').html(actual_price + ((item_price + price_of_options) * quantity_dif));
}
else {
quantity_dif *= -1;
quantity = parseInt($(element).find('[data-quantity]').val());
$(element).find('[data-item-total]').html((item_price + price_of_options) * new_quantity);
$('[data-total]').html(actual_price - ((item_price + price_of_options) * quantity_dif));
}
quantity = parseInt($(element).find('[data-quantity]').val());
})
})
})
As I said, code is working: https://jsfiddle.net/redbean/4dy38ye4/1/ Just not when i'm reloading the webpage.
I'm not english, be kind about this. I'm trying to do the best to be clear!
I have a text input called "textmoney". In my jQuery i have a variable called "dailyE". This var is basically "textmoney".val / 365. This whould show an estimated amount made daily. What i can't get to work is my "stats", which basically show statistics of the number inputted in "textmoney". I can't get it to display a simple math function in statFunction. I've tried to fix this for a while now.
here is my jQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
var $demo = $('#demo');
var $textMoney = $('#textmoney');
var $moneydiv = $('#moneydiv');
var $stat = $('#stat');
var dailyE = $textMoney.val() / 365;
var $second = (dailyE / 24) / 60 / 60 / 60;
var $minute = (dailyE / 24) / 60 / 60;
var $hour = (dailyE / 24);
var $day = dailyE;
var $week = dailyE * 7;
var $month = (dailyE * 7) * 30;
var $year = (dailyE * 7) *30 *12;
var $secondp = $('#second');
var $minutep = $('#minute');
var $hourp = $('#hour');
var $dayp = $('#day');
var $weekp = $('#week');
var $monthp = $('#month');
var $yearp = ('#year');
$('#stat').hide();
function getmoney(){
var money = $textMoney.val();
if (isNaN(money) || money === '') {
$demo.text('You aint enter no $$$$$$');
} else {
var dailyE = $textMoney.val() / 365;
$demo.text('$' + dailyE + ' per day');
}
}
function statFunction() {
$stat.show();
$secondp.text("$second");
}
// on enter key
$textMoney.keydown(function(e) {
if (e.which === 13) {
getmoney();
$('#stat').show();
} else if ($(this).val() === '') {
$demo.text('');
$('#stat').hide();
}
}).mouseover(function() {
$(this).css('border', '1px solid black');
}).mouseout(function() {
$(this).css('border', '1px solid grey');
});
// on click
$moneydiv.click(function(){
getmoney();
$('#stat').show();
});
$stat.click(function() {
statFunction();
})
});
</script>
missing $ for var $yearp = ('#year');
Please correct it as
var $yearp = $('#year');
I'm trying to use the below code to reflect different pictures of the moon into an HTML doc. Of course i've added the Jquery and Javascript tags.
I've been looking at this for hours and trying different things but I can't find out what to put into HTML code that will actually show or echo the pictures.
What should I put into the "moonImage.src = "pix/moon" + truncPhase + ".png";" part of the code? I don't understand how to essentially echo the photos. Help please?:
// Image max size
var IMAGE_MAX_SIZE = 196;
// Records whether or not the gadget is expanded
var poppedOut = false;
function onOpen() {
// Check once every 30 minutes
view.setInterval(onTimer, 30 * 60 * 1000);
// Initialize the gadget
onTimer();
}
// Called when the timer goes off
function onTimer() {
// Compute the moon phase each time timer is called
var cal = new Date();
// Base the computation off of UTC time, to the nearest hour
var phase = computeMoonPhase(cal.getUTCFullYear(),
cal.getUTCMonth() + 1,
cal.getUTCDate(),
cal.getUTCHours());
var truncPhase = Math.floor(phase) % 30;
// Find the text description of the current phase
var desc;
if (truncPhase === 0) {
desc = STRING_MOON_DESC_NEW;
} else if (truncPhase == 7) {
desc = STRING_MOON_DESC_FIRST_QUARTER;
} else if (truncPhase == 15) {
desc = STRING_MOON_DESC_FULL;
} else if (truncPhase == 23) {
desc = STRING_MOON_DESC_THIRD_QUARTER;
} else if (truncPhase > 0 && phase < 7) {
desc = STRING_MOON_DESC_WAXING_CRESCENT;
} else if (truncPhase > 7 && phase < 15) {
desc = STRING_MOON_DESC_WAXING_GIBBOUS;
} else if (truncPhase > 15 && phase < 23) {
desc = STRING_MOON_DESC_WANING_GIBBOUS;
} else {
desc = STRING_MOON_DESC_WANING_CRESCENT;
}
// Set the image and text component appropriately
moonImage.src = "pix/moon" + truncPhase + ".png";
moonImage.tooltip = (Math.floor(phase * 100) / 100) + " " + STRING_DAYS_OLD;
phaseAge.innerText = STRING_MOON_AGE_PREFIX + " " + moonImage.tooltip +
"\n" +
desc;
}
// Called when view is resized (recompute constituent basicElement sizes and
// locations)
function resizeView() {
setDimensions(event.width, event.height);
}
// Open the browser whenever a user double clicks (expanded or collapsed)
function onDblClick() {
var obj = new ActiveXObject("Shell.Application");
obj.Open("http://stardate.org/nightsky/moon/");
}
// Show date age in title, when gadget is minimized
function onMinimize() {
view.caption = STRING_MOON_SHORT + " - " + moonImage.tooltip;
}
// Only show the textual part (details) when popped out
function onPopout() {
poppedOut = true;
phaseAge.visible = true;
}
// Hide the textual part in restored mode, show regular title, and reset
// dimensions
function onRestore() {
view.caption = GADGET_NAME;
phaseAge.visible = false;
//moonImage.enabled = true;
poppedOut = false;
setDimensions(view.width, view.height);
}
// Called whenever the sizes and/or locations of basicElements need to change
function setDimensions(width, height) {
// Image is square, constrained by smallest dimension
var sz = Math.min(width, height);
// Make the image almost as large as the sz
moonImage.width = Math.min(IMAGE_MAX_SIZE, sz * 0.9);
moonImage.height = Math.min(IMAGE_MAX_SIZE, sz * 0.9);
if (poppedOut) {
// Align image on left, and set text location
moonImage.x = 0;
phaseAge.x = moonImage.width + 5;
phaseAge.y = (height - phaseAge.height) / 2;
} else {
// Center image horizontally
moonImage.x = (width - moonImage.width) * 0.5;
}
// Always center image vertically
moonImage.y = (height - moonImage.height) * 0.5;
}
// Compute the moon phase.
// Code is based upon Bradley E. Schaefer''s well-known moon phase algorithm.
function computeMoonPhase(year, month, day, hours) {
var MOON_PHASE_LENGTH = 29.530588853;
// Convert the year into the format expected by the algorithm
var transformedYear = year - Math.floor((12 - month) / 10);
// Convert the month into the format expected by the algorithm
var transformedMonth = month + 9;
if (transformedMonth >= 12) {
transformedMonth = transformedMonth - 12;
}
// Logic to compute moon phase as a fraction between 0 and 1
var term1 = Math.floor(365.25 * (transformedYear + 4712));
var term2 = Math.floor(30.6 * transformedMonth + 0.5);
var term3 = Math.floor(Math.floor((transformedYear / 100) + 49) * 0.75) - 38;
var intermediate = term1 + term2 + (day + (hours - 1) / 24) + 59;
if (intermediate > 2299160) {
intermediate = intermediate - term3;
}
var normalizedPhase = (intermediate - 2451550.1) / MOON_PHASE_LENGTH;
normalizedPhase = normalizedPhase - Math.floor(normalizedPhase);
if (normalizedPhase < 0) {
normalizedPhase = normalizedPhase + 1;
}
// Return the result as a value between 0 and MOON_PHASE_LENGTH
return normalizedPhase * MOON_PHASE_LENGTH;
}
HTML:
<html>
<head><title>Kendrick Moon</title>
<script src="ajax.googleapis.com/ajax/libs/jquery/1.8.3/ (etc.)
<script src="code.jquery.com/ui/1.9.2/jquery-ui.js"></script>;
<script src="main.js" type="text/javascript"></script>
<head>
<body>
<div><img src=""/> </div>
</body>
</html>
ok, well thats then easy.
first of all, you might want to check out jquery. with jquery it would be something like this.
<img src="" id="my_image" />
in javascript then (with jquery)
// the `myLinkToImage` is hopefully the variable of your path
$("#my_image").attr("src", myLinkToImage);
as you can see I´m using #. That is a typical jQuery Selector. You might check out more of them here
in javascript without jquery
document.getElementById("my_image").src = myLinkToImage;
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);
}