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
Related
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>
I have been developing a site that will provide schedules created by people. I'm using Alienware to develop it and the ajax code works perfectly on the laptop all of the time. I am using IE. However, if I access my site on my Samsung Smart TV or my HTC U11 phone, Ajax isn't consistent. It displays the data I am requesting, however, when I sum up a total of hours for the week, it sometimes displays the correct hours, or sometimes shows 0 hours, when the user is scheduled for the week. Why is it inconsistent between devices? I know that Ajax is recommended for IE. As I said, though, it sometimes will display the correct total weekly hours, and other times it will just show zero. This issue isn't occurring on my Alienware.
I've already tried using onload instead of onreadystatechange. I've set the request to asynchronous and synchronous. Whether it's set to true or false, on my other devices, it fails to be consistent. I've tried it as a post and get method, and both also are inconsistent. What is wrong with my code?
function getThisWeek(str5) {
lastDate = new Date(str5);
// getting dates for this week to be displayed...
this.math = dayInput.length - 1;
this.math0 = 0 - new Date(str5).getDay();
// getting week total hour length, to determine how many times this code executes...
weekSum = 0;
totals = [];
for (this.i = 0; this.i < weekTotalHours.length; this.i++) {
str3 = this.i;
this.date = new Date(str5);
for (this.ii = (this.i * (7)) - new Date().getDay(); this.ii < (7 * (this.i + 1)) - new Date().getDay(); this.ii++) {
totalHours = 0;
this.date = new Date(str5);
this.date = new Date(this.date.setDate(this.date.getDate() + (this.ii)));
// which element position the total daily hours belongs to when displaying them...
this.pos = this.ii + new Date().getDay();
thisDayChart[this.pos].innerHTML = "";
// displaying the date
dayInput[this.pos].innerHTML = this.date.getDate();
// highlighting today's date...
if (this.date.getDate() == new Date(str5).getDate() && this.date.getMonth() == new Date().getMonth()) {
dayInput[this.pos].style.color = "white";
dayInput[this.pos].style.backgroundColor = "silver";
dayInput[this.pos].style.borderRadius = "0px";
thisDay[this.pos].style.border = "2px double lightblue";
} else {
dayInput[this.pos].style.color = "";
dayInput[this.pos].style.backgroundColor = "";
dayInput[this.pos].style.borderRadius = "";
thisDay[this.pos].style.border = "";
}
// getting schedule from database...
this.xmlhttp = new XMLHttpRequest();
this.xmlhttp.pos = this.pos;
this.xmlhttp.ipos = this.i;
this.xmlhttp.d = months[this.date.getMonth()] + " " + this.date.getDate() + ", " + this.date.getFullYear();
this.xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//alert(this.responseText);
dayInput[this.pos].m = months[new Date(this.d).getMonth()];
dayInput[this.pos].weekDay = days[new Date(this.d).getDay()];
// how many weeks in the year is user...
this.islpyr = new Date(this.d);
this.islpyr = this.islpyr.setMonth(1);
this.islpyr = new Date(new Date(this.islpyr).setDate(29));
if (this.islpyr.getMonth() == 2) {
mlens[1] = 28;
} else {
mlens[1] = 29;
}
// getting total amount of days for the year...
this.yrlen = 0;
for (this.iii = 0; this.iii < mlens.length; this.iii++) {
this.yrlen += mlens[this.iii];
}
// getting total weeks
this.wklen = this.yrlen / 7;
this.wklen = Math.round(this.wklen);
this.week = 0;
for (this.iii = 0; this.iii < new Date(this.d).getMonth(); this.iii++) {
this.week += mlens[this.iii];
}
this.week += new Date(this.d).getDate();
this.week /= 7;
this.week = Math.round(this.week) + 1;
// rounding and displaying current week number...
if (new Date(this.d).getDay() == 0) {
myDayWrapper[this.ipos].weekLabel = "Week " + this.week + " of " + this.wklen;
}
if (this.pos == 0) {
weekDisplay[0].innerHTML = myDayWrapper[0].weekLabel;
}
// which day of the year it is... how many days in the year is the user...
this.yrpos = 0;
for (this.iv = 0; this.iv < new Date(this.d).getMonth(); this.iv++) {
this.yrpos += mlens[this.iv];
}
this.yrpos += new Date(this.d).getDate();
thisDayTitle[this.pos].innerHTML = "Day " + this.yrpos + " of " + this.yrlen;
totalHours = 0;
this.schedule = "" + this.responseText;
// if user is unscheduled, do this first... 'undefined' literally means there isn't a schedule for that specific day.
if (this.schedule.search("Undefined") >= 0) {
this.elem = document.createElement("div");
this.elem.setAttribute("class","not_scheduled");
this.elem.innerHTML = "Unscheduled";
thisDayChart[this.pos].appendChild(this.elem);
this.elem = document.createElement("div");
this.elem.setAttribute("class","pick_up_shift_btn");
this.elem.innerHTML = "Claim Shifts";
this.elem.i = this.pos;
this.elem.ipos = this.ipos;
this.elem.onclick = function() {
popUpWrap[1].style.display = "block";
this.datesd = [];
for (this.i = this.ipos * 7; this.i < 7 * (this.ipos + 1); this.i++) {
this.datesd.push(dayInput[this.i].innerHTML);
}
for (this.i = 0; this.i < 7; this.i++) {
shiftClaimDate[this.i].innerHTML = this.datesd[this.i];
popUpShiftDay[this.i].innerHTML = dayInput[this.i].weekDay;
this.strrr = "" + dayInput[this.i].m;
this.strrr = this.strrr.substring(0,3);
shiftClaimMonth[this.i].innerHTML = this.strrr;
}
}
thisDayChart[this.pos].appendChild(this.elem);
if (totals.length - 1 == this.pos) {
} else {
totals.push(0);
}
} else {
// getting daily total...
this.schedule = this.schedule.split(",");
for (this.iii = 0; this.iii < this.schedule.length; this.iii++) {
this.str = "" + this.schedule[this.iii];
this.str = this.str.split("=");
this.dateString = "December 22, 1991";
switch (this.str[0]) {
case "shift_start":
this.start = new Date(this.dateString + " " + this.str[1]);
this.end = this.schedule[this.schedule.length - 1] + "";
this.end = this.end.split("=");
this.end = new Date(this.dateString + " " + this.end[1]);
this.hours = (this.end.getHours() - this.start.getHours()) * 60;
this.hours = this.hours - (this.start.getMinutes() + this.end.getMinutes());
this.hours /= 60;
totalHours += this.hours;
weekSum += totalHours;
break;
case "break_start":
this.start = new Date(this.dateString + " " + this.str[1]);
this.end = this.schedule[this.iii + 1] + "";
this.end = this.end.split("=");
this.end = new Date(this.dateString + " " + this.end[1]);
this.hours = (this.end.getHours() - this.start.getHours()) * 60;
this.hours = this.hours - (this.start.getMinutes() + this.end.getMinutes());
this.hours /= 60;
weekSum -= this.hours;
totalHours -= this.hours;
this.s = "s";
if (totalHours == 1) {
this.s = "";
}
thisDayChart[this.pos].innerHTML = totalHours + " hour" + this.s;
break;
}
}
}
weekTotalHours[this.ipos].innerHTML = "Week Total: " + weekSum;
//alert(weekSum);
// displaying hour totals...
if (new Date(this.d).getDay() == 6) {
weekSum = 0;
}
totalHours = 0;
}
}
this.xmlhttp.open("GET","/js/data/schedule.html?date="+ months[this.date.getMonth()] + " " + this.date.getDate() + ", " + this.date.getFullYear(),false);
this.xmlhttp.send();
}
}
}
I expect every device to be consistent with the hour total it should be displaying, on every device that Ajax should work on.
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 table that calculates a total depending on the input the user types. My problem is that the jquery code is calculating each key stroke and not "grabbing" the entire number once you stop typing. Code is below, any help woud be greatly appreciated.
$(document).ready(function() {
$('input.refreshButton').bind('click', EstimateTotal);
$('input.seatNumber').bind('keypress', EstimateTotal);
$('input.seatNumber').bind('change', EstimateTotal);
});
//$('input[type=submit]').live('click', function() {
function EstimateTotal(event) {
var tierSelected = $(this).attr('data-year');
var numberSeats = Math.floor($('#numberSeats_' + tierSelected).val());
$('.alertbox_error_' + tierSelected).hide();
if (isNaN(numberSeats) || numberSeats == 0) {
$('.alertbox_error_' + tierSelected).show();
} else {
$('.alertbox_error_' + tierSelected).hide();
var seatHigh = 0;
var seatLow = 0;
var seatBase = 0;
var yearTotal = 0;
var totalsArray = [];
var currentYear = 0;
$('.tier_' + tierSelected).each(function() {
seatLow = $(this).attr('data-seat_low');
firstSeatLow = $(this).attr('data-first_seat_low');
seatHigh = $(this).attr('data-seat_high');
seatBase = $(this).attr('data-base_cost');
costPerSeat = $(this).attr('data-cost_per_seat');
years = $(this).attr('data-year');
seats = 0;
if (years != currentYear) {
if (currentYear > 0) {
totalsArray[currentYear] = yearTotal;
}
currentYear = years;
yearTotal = 0;
}
if (numberSeats >= seatHigh) {
seats = Math.floor(seatHigh - seatLow + 1);
} else if (numberSeats >= seatLow) {
seats = Math.floor(numberSeats - seatLow + 1);
}
if (seats < 0) {
seats = 0;
}
yearTotal += Math.floor(costPerSeat) * Math.floor(seats) * Math.floor(years) + Math.floor(seatBase);
});
totalsArray[currentYear] = yearTotal;
totalsArray.forEach(function(item, key) {
if (item > 1000000) {
$('.totalCost_' + tierSelected + '[data-year="' + key + '"]').append('Contact Us');
} else {
$('.totalCost_' + tierSelected + '[data-year="' + key + '"]').append('$' + item);
}
});
}
}
You'll need a setTimeout, and a way to kill/reset it on the keypress.
I'd personally do something like this:
var calc_delay;
$(document).ready(function() {
$('input.refreshButton').bind('click', runEstimateTotal);
$('input.seatNumber').bind('keypress', runEstimateTotal);
$('input.seatNumber').bind('change', runEstimateTotal);
});
function runEstimateTotal(){
clearTimeout(calc_delay);
calc_delay = setTimeout(function(){ EstimateTotal(); }, 100);
}
function EstimateTotal() {
....
What this does is prompt the system to calculate 100ms after every keypress - unless another event is detected (i.e. runEstimateTotal is called), in which case the delay countdown resets.
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);
}