Floating point number calculation - javascript

I'm new to working with bitcoin and I made a javascript that adds 10 satoshi every second and then it displays on the screen in BTC.
Can someone show me why it starts showing strange numbers and then the decimal points are incorrect? I need it to start with 0.00000010 BTC
var start = 0;
window.setInterval(
function() {
start = start + 10;
var btc = start / 100000000;
console.log(btc + " BTC");
}, 1000);

toFixed() method will do the trick in this case, and you will also have to increment with 0.00000010 if you want it to start from that. See the working snippet below please:
var start = 0;
window.setInterval(
function() {
start = start + 0.00000010;
var btc = start.toFixed(8);
document.getElementById("start").innerHTML = btc + " BTC";
}, 1000);
<p id='start'></p>

By using toFixed() you get the results:-)
var start = 0 ;
window.setInterval(function () {
start = start + 10;
var btc = parseFloat(start / 100000000).toFixed(8);
console.log(btc + " BTC");
}, 1000);

Related

JavaScript calculates my economic growth

I have a JS script and a div with "counter" id:
var START_DATE = new Date("January 1, 2017 00:00:00"); // data de start
var INTERVAL = 1; // in secunde
var INCREMENT = 1400.53; // crestere per secunda
var START_VALUE = 1400.53; // valoare initiala
var count = 0;
window.onload = function() {
var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt(((now - START_DATE)/msInterval) * INCREMENT + START_VALUE);
document.getElementById('counter').innerHTML = count;
setInterval("count += INCREMENT; document.getElementById('counter').innerHTML = parseInt(count);", msInterval);
};
<div id="counter"></div>
This script calculates my economic growth per second from the beginning of 2017 after a certain amount.
So my problem is: I have 5 different START_VALUE number so I need to export 5 counters in 5 divs. How can I use the same code but not to duplicate the whole script? What I need to change is only var START_VALUE and var INCREMENT!?
There are great resources for learning basic Javascript. A simple Google search will direct you to something like this.
The easiest way to reuse code is by creating a function. Functions take arguments that change the output based on what you input. You can think of it kind of like f(x) = x^2 in mathematics, where x is the input and you get some output y.
In your case, the function would look something like this:
var START_DATE = new Date("January 1, 2017 00:00:00"); // data de start
var INTERVAL = 1; // in secunde
var count = 0;
function countFunc(id, start_value, increment) {
var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt(((now - START_DATE)/msInterval) * increment + start_value);
document.getElementById(id).innerHTML = count;
setInterval("count += " + increment + "; document.getElementById('" + id + "').innerHTML = parseInt(count);", msInterval);
}
countFunc("counter1", 1000, 1000);
countFunc("counter2", 1400, 1400);
countFunc("counter3", 1500, 1500);
countFunc("counter4", 1600, 1600);
countFunc("counter5", 1000, 1000);
<div id="counter1"></div>
<div id="counter2"></div>
<div id="counter3"></div>
<div id="counter4"></div>
<div id="counter5"></div>
Notice how I hardly changed your code, except for the things that needed to change. You were on the right track. The start value and the increment need to change. In this case, the id also needs to change for every div.
Try work with JSON:
var START_DATE = new Date("January 1, 2017 00:00:00"); // data de start
var INTERVAL = 1; // in secunde
var FULL_DATA = [
{START_VALUE: 1400.53, INCREMENT: 1400.53, count: 0 },
{START_VALUE: 1401.53, INCREMENT: 1401.53, count: 0 },
{START_VALUE: 1402.53, INCREMENT: 1402.53, count: 0 },
{START_VALUE: 1403.53, INCREMENT: 1403.53, count: 0 },
{START_VALUE: 1404.53, INCREMENT: 1404.53, count: 0 }
]
var msInterval = INTERVAL * 1000;
var now = new Date();
function inc(){
for(var i in FULL_DATA){
var data = FULL_DATA[i];
if (data.count == 0){
data.count = parseInt(((now - START_DATE)/msInterval) * data.INCREMENT + data.START_VALUE);
}else{
data.count += data.INCREMENT;
}
document.getElementById('counter' + i).innerHTML = parseInt(data.count);
}
}
setInterval(inc, msInterval);
<div id="counter0"></div>
<div id="counter1"></div>
<div id="counter2"></div>
<div id="counter3"></div>
<div id="counter4"></div>

Increment Bitcoin Numerif Format Javascript

Hello why i try to coding something like a counter for bitcoin. this is the Code
result: <div id="counter"></div>
This is the Html
This is Javascript Code
var INTERVAL = 1; // in seconds
var INCREMENT = (0.00000001).toFixed(8); // increase per tick
var START_VALUE = (0.00000001).toFixed(8); // initial value when it's the start date
var count = 0;
$(document).ready(function() {
var msInterval = INTERVAL * 3000;
count = INCREMENT + START_VALUE;
document.getElementById('counter').innerHTML = count;
window.setInterval( function(){
count += INCREMENT;
document.getElementById('counter').innerHTML = count;
}, msInterval);
});
Heres the Output you can check
https://jsfiddle.net/8eqc2b3t/
Can anyone help
First of all, I've modified your code a little to make a bit more sense, you're using a few keywords that could be reserved within certain languages, so I'd avoid that in future ( like using count as a variable name )
var interval = 1; // in seconds
var increasePerTick = (0.00000001).toFixed(8); // increase per tick
var startingValue = (0.00000001).toFixed(8); // initial value
var $counter = $('#counter');
var btcAmount = 0.00000000;
$(document).ready(function() {
var msInterval = interval * 1000; // Convert to Milliseconds
$counter.text(startingValue); // Set initial amount
window.setInterval( function(){
btcAmount = (parseFloat(btcAmount)+parseFloat(increasePerTick)).toFixed(8);
$counter.text(btcAmount);
}, msInterval);
});
The main issue was that when you were using the + operand you were adding to the string rather than adding the two floats together. You'd also not added jQuery to your Fiddle, causing it not to work, I've fixed this and shown how to do the calculation here too, which basically is to parse both the floats, set them toFixed(8) and then print them to the counter.
The addition part is here:
btcAmount = (parseFloat(btcAmount)+parseFloat(increasePerTick)).toFixed(8);
You were also converting your msInterval incorrectly. Now seconds in interval should work out correctly when changed.
Hope this helps.
Edit:
Forgot to add the Fiddle, sorry! : https://jsfiddle.net/20Lppogq/

Changing part of a image url every x amount of seconds

Alright so my question today is bit of a weird one. Basically what I'm trying to do is take this image code
<img src="3d.php?a=-25&w=35&wt=-45&abg=0&abd=-30&ajg=-25&ajd=30&ratio=13&format=png&displayHairs=true&headOnly=false&login=">
and have it update only the w=35 part of it and have it add +1 to that number, either forever or until it hits 360 then resets it to 0, every x amount of seconds.
The point of this is to create what looks like a spinning image, instead of spawning each possible wt= from 0 to 360 by hand.
Try this:
<img id="threedee">
In your script, further down the page:
var w = 35;
var x = 5; // every 5 seconds
var threedee = document.getElementById("threedee");
setInterval(function () {
w = (w + 1) % 360;
var src = "3d.php?a=-25&w=" + w + "&wt=-45&abg=0&abd=-30&ajg=-25&";
src += "ajd=30&ratio=13&format=png&displayHairs=true&headOnly=false&login=";
threedee.src = src;
}, x * 1000);
You can try something like
var counter = 35;
var x = 5;
var url = '3d.php?a=-25&w={{counter}}&wt=-45&abg=0&abd=-30&ajg=-25&ajd=30&ratio=13&format=png&displayHairs=true&headOnly=false&login='
setInterval(function(){
img.src = url.replace('{{counter}}',counter);
counter = counter + 1 > 360 ? 0 : counter + 1;
},x * 1000);

Increment from zero to number in a set time

I am trying to increment from 0 to a number (can be any number from 2000 to 12345600000) within a certain duration (1000 ms, 5000 ms, etc). I have created the following:
http://jsfiddle.net/fmpeyton/c9u2sky8/
var counterElement = $(".lg-number");
var counterTotal = parseInt(counterElement.text()/*.replace(/,/g, "")*/);
var duration = 1000;
var animationInterval = duration/counterTotal;
counterElement.text("0");
var numberIncrementer = setInterval(function(){
var currentCounterNumber = parseInt(counterElement.text()/*.replace(/,/g, "")*/);
if (currentCounterNumber < counterTotal){
currentCounterNumber += Math.ceil(counterTotal/duration);
// convert number back to comma format
// currentCounterNumber = addCommas(currentCounterNumber);
counterElement.text(currentCounterNumber);
} else {
counterElement.text(counterTotal);
clearInterval(numberIncrementer);
}
console.log("run incrementer");
}, animationInterval);
function addCommas(number){
for (var i = number.length - 3; i > 0; i -= 3)
number = number.slice(0, i) + ',' + number.slice(i);
return number;
}
And this somewhat works, but it does not respect the duration. I.e. if you increase the number from 1000 to 1000000000, they both take different amounts of time to reach the destination number.
How can I increment from zero to a number in a specific time frame?
As #Mouser pointed out, the issue is that the animationInterval can't be too small (the actual minimum threshold will vary based on the browser and platform). Instead of varying the interval, vary the increment to the counter:
var counterElement = $(".lg-number");
var counterTotal = parseInt(counterElement.text()/*.replace(/,/g, "")*/);
var duration = 1000;
var animationInterval = 10;
var startTime = Date.now();
counterElement.text("0");
var numberIncrementer = setInterval(function(){
var elapsed = Date.now() - startTime;
var currentCounterNumber = Math.ceil(elapsed / duration * counterTotal);
if (currentCounterNumber < counterTotal){
counterElement.text(currentCounterNumber);
} else {
counterElement.text(counterTotal);
clearInterval(numberIncrementer);
}
console.log("run incrementer");
}, animationInterval);
I played around with your fiddle and found that the delay needs to be higher. At 8ms or 16ms, it is accurate enough to handle a second, but not accurate enough to handle half a second. From experimenting, it seems like a delay of 64ms is small enough to seem like it's incrementing smoothly, but big enough to have an accurate effect.
The difference is that the current number is calculated based on the process rather than directly manipulated.
var counterElement = $(".lg-number");
var counterTotal = parseInt(counterElement.data('total'));
var interval = 0;
var duration = parseInt(counterElement.data('duration'));;
var delay = 64
var numberIncrementer = setInterval(function(){
var currentCounterNumber = 0;
interval += delay;
if (interval <= duration){
var progress = interval / duration;
currentCounterNumber = Math.round(progress * counterTotal);
} else {
currentCounterNumber = counterTotal
clearInterval(numberIncrementer);
}
counterElement.text(currentCounterNumber);
}, delay);
http://jsfiddle.net/c9u2sky8/5/
Also: Javascript timers are not perfectly accurate. But this should be accurate enough for UI use cases.

Increment integer by 1; every 1 second

My aim is to create identify a piece of code that increments a number by 1, every 1 second:
We shall call our base number indexVariable, I then want to: indexVariable = indexVariable + 1 every 1 second; until my indexVariable has reached 360 - then I wish it to reset to 1 and carry out the loop again.
How would this be possible in Javascript? - if it makes a difference I am using the Raphael framework.
I have carried out research of JavaScript timing events and the Raphael delay function - but these do not seem to be the answer - can anyone assist?
You can use setInterval() for that reason.
var i = 1;
var interval = setInterval( increment, 1000);
function increment(){
i = i % 360 + 1;
}
edit: the code for your your followup-question:
var interval = setInterval( rotate, 1000);
function rotate(){
percentArrow.rotate(1,150,150);
}
I'm not entirely sure, how your rotate works, but you may have to store the degrees in a var and increment those var too like in the example above.
var indexVariable = 0;
setInterval(function () {
indexVariable = ++indexVariable % 360 + 1; // SET { 1-360 }
}, 1000);
Try:
var indexVariable = 0;
setInterval(
function () {
indexVariable = (indexVariable + 1) % 361;
}, 1000}

Categories

Resources