Calculation of per unit of Electricity [closed] - javascript

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);
}

Related

Javascript to calculate and display odds as their simplest fraction

I'm writing a bit of script for the WooCommerce product page that takes the quantity entered in the qty input field and displays some text based on that qty:
function reduce(numerator,denominator){
var gcd = function gcd(a,b){
return b ? gcd(b, a%b) : a;
};
gcd = gcd(numerator,denominator);
return [numerator/gcd,denominator/gcd];
}
jQuery('.qty').on('change', function() {
showOdds();
});
function showOdds() {
var qty = 1; // hard coded for testing
var min = 200; // hard coded for testing
var sofar = 40; // hard coded for testing
var plural = '';
var total = 0;
var odds = '';
if (qty > 1){
plural = 'tickets';
}
else{
plural = 'ticket';
}
if (qty > 0){
if ((qty + sofar) > min){
total = qty + sofar;
odds = reduce(qty, total);
}
else {
odds = reduce(qty, min);
}
var text = document.createElement('p');
text.className = 'product-odds';
text.innerHTML = 'Max odds of ' + qty + ' ' + plural + ' winning is ' + odds + '.';
var theDiv = document.getElementById('odds');
theDiv.appendChild(text);
}
}
jQuery(document).ready(function loadPage() {
showOdds();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='odds'></div>
The current output:
Max odds of 1 ticket winning is 1,200
How can I make the odds display in their simplest fraction form? For example if there are 200 tickets available and '1' is entered, it should show '1/200' but if someone enters '20' it should show '1/10'. The 'total' figure will eventually be picked up from the page rather than a fixed value too.
I can use the gcd as posted here but how can I get the two numbers from the array and display them as a fraction (with the /) in the required div?
You can return the desired string instead of array. Check the snippet below.
I've changed return [numerator/gcd,denominator/gcd]; to return numerator/gcd+'/'+denominator/gcd;
function reduce(numerator,denominator){
var gcd = function gcd(a,b){
return b ? gcd(b, a%b) : a;
};
gcd = gcd(numerator,denominator);
return numerator/gcd+'/'+denominator/gcd;
}
jQuery('.qty').on('change', function() {
showOdds();
});
function showOdds() {
var qty = 1; // hard coded for testing
var min = 200; // hard coded for testing
var sofar = 40; // hard coded for testing
var plural = '';
var total = 0;
var odds = '';
if (qty > 1){
plural = 'tickets';
}
else{
plural = 'ticket';
}
if (qty > 0){
if ((qty + sofar) > min){
total = qty + sofar;
odds = reduce(qty, total);
}
else {
odds = reduce(qty, min);
}
var text = document.createElement('p');
text.className = 'product-odds';
text.innerHTML = 'Max odds of ' + qty + ' ' + plural + ' winning is ' + odds + '.';
var theDiv = document.getElementById('odds');
theDiv.appendChild(text);
}
}
jQuery(document).ready(function loadPage() {
showOdds();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='odds'></div>

Calculation of JQuery in while loop

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.

Parsing BTC jQuery calculator to USD

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

Solve mathematical function in javascript

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!

Pricing Variations v2

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));
}
}

Categories