Loop logic formatting number - javascript

I'm new at javascript and trying to do some loop that will automaticly will format a number (1000 = 1K , 10000 = 10k 100000 = 100k )
formatting to 1K works and then it stops for some reason...
for me this loop makes sense :
loop will cycle once so the condition will be true , this will give me the first 2 integers and a 'K', after that the loop will break
if condition is not true , loop should be continue...
this is probaly not the ideal way to do it , but i wondering why my logic thinking is wrong
thanks advanced and sorry for my bad english.
<body >
<p>Number: <span id="number"></span></p>
<script>
len=1;
thousand=1000;
million =1000000;
num= 10001;
for(thousand;thousand<million;thousand*=10){ //when thousand is less then a million , multiply thousand times 10
if(num>=thousand && num<(thousand*10)){ // should cycle the loop twice so i got num>=10000 && num<100000
document.getElementById("number").innerHTML = num.toString().substring(0,len)+" K";
len+=1; // increase by 1 , so i will get 10 K instead of 1 K
break; // should break now since condition is true after second cycle
}
}
// probaly not the ideal method to do this , i just want to know my problem because this loop makes sense to me....
</script>
</body>

A loop just makes no sense in this case, because you don't have an array type to iterate over.
Additionally generating a range to loop, like you are tyring to do isn't worth, since you could just
n = Math.floor(n / 1000) + 'k';
see chrisz answer for a working 'number to k' filter.
If you really want to loop. Try this:
let n = 3024;
for (let i = 0; i < 1000; i++) {
if (n >= i * 1000 && n < (i + 1) * 1000) {
console.log(i + 'k');
break;
}
}

Related

JavasScript Add half a percent to a number any amount of times I choose

Hi I need a block of code for some math that I'm trying to work out. The code I'm looking for will be able to add half a percent (0.005) to a number and return the result back to me. I need the code to take two separate inputs, the first is the start number, and the second is how many times I want the loop to execute. An example would be if I started with 7000 the code should output ~7321.37 (if possible let it stop after 2 decimal points). Thank you for the help in advance!
Code example of what I'm trying to do:
function growth(initialValue, timesOfExecution)` {
let answer;
let execute;
while (execute > 0) {
answer = initialValue + initialValue(0.05)
execute--
}
return answer;
}
console.log(growth(7000, 9))
Here you go:
function growth(initialValue, timesOfExecution) {
for (let i = 0; i < timesOfExecution; i++) {
initialValue = initialValue + (initialValue * 0.005)
}
return initialValue.toFixed(2);
}
console.log(growth(7000, 9))

Divide 100 in equal percentages in JavaScript

Ok. I will try to explain my case as good as I can.
Basically, I have this function here that will add an increment to my bootstrap progressbar:
function progress(increment) {
f = parseInt(document.getElementsByClassName('progress-bar')[0].style.width);
document.getElementsByClassName('progress-bar')[0].style.width = (f + increment) +'%';
}
Now for each step, for instance there are 6 steps, I must divide 100 into 6 steps incrementally.
For instance, if we are in step 1: 100 / 6 = 16.67 each so this must add 16.67 incrementally.
So it would be like this:
Step 1: Add 16.67
Step 2: Add 33.34
Step 3: Add 50.01
---- and the list go on
So on my program I have the ff variables:
let current_step = 0;
let stepCount = 6
So if I used the progress function, I tried dividing 100 to stepCount to the current_step:
progress(100 / (stepCount - current_step)
But this did not resolve the issue and I am getting only weird numbers.
Any idea what's the proper formula here to get the right numbers to add on the progressbar?
PS. Sorry, I hope its not that confusing. I tried to explain this at the best I can.
Your calculation isn't correct. This should give you the correct value.
progress((100 / stepCount) * current_step);
function progress(value) {
document.getElementsByClassName('progress-bar')[0].style.width = `${value}%`;
}
or you can do it like this
progress(100 / stepCount);
function progress(increment) {
let f = +document.querySelector('.progress-bar')[0].style.width.slice(0, -1);
// I'm slicing the width to remove the `%`
document.getElementsByClassName('progress-bar')[0].style.width = `${f + increment}%`;
}

How to create number suffixes such as "100K" without having to be repetitive?

I've been having a problem that when my auto clicker in my clicker game goes fast enough to get to 200 thousand, it starts to lag, and then it doesn't function properly, or as fast.
Is there a way to make 100 thousand turn into 100K, and 101 thousand turn into 101K without being repetitive?
I tried this with my original code, and realized putting up to 1000 suffixes into each function would be a little too hard:
if (number >= 100000) {
document.getElementById(ID).innerHTML = "100K"
}
if (number >= 101000) {
document.getElementById(ID).innerHTML = "101K"
}
and on and on.
I don't want multiple if statements!
This would work, but it would take up way too much space, and I know there is an easier way to it, but I just couldn't find it. Can anyone provide a way to do this?
Try separating the job of formatting your number into a different function.
SUFFIXES = 'KMBTqQsSOND' // or whatever you'd like them to be
function getSuffixedNumber(num) {
var power = Math.floor(Math.log10(num));
var index = Math.floor(power / 3);
num = Math.round(num / Math.pow(10, (index * 3))); // first 3 digits of the number
return num + (SUFFIXES[index - 1] || ''); // default to no suffix if we get an out of bounds index
}
You can call the function like this: var x = getSuffixedNumber(101000), the value of x will be "101K".

Using a for loop and document.getElementById to populate an array in Javascript

I have been trying to populate an array using a for loop and taking such values using document.getElementById("spin " + i).value;
The ids on my html for every input tag go from spin1 to spin18.
Any suggestions on what I am doing wrong? Or what I can change?
var nums = [];
for(var i = 1; i <= 18; i++){
var num[i] = parseInt(document.getElementById("spin" + i).value);
nums.push(num[i]);
}
alert(nums.length);
What is the problem? You never mention what kind of results being generated or what the front-end html code looks like.
The js looks compilable, but here are some pointers.
The number 0 is before 1
It's a good habit to get in this mind set, plus it might save you from making stupid mistakes later on. Anyway, just to reinforce this, below is a number chart.
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
Avoid unnecessary variables
Having a js compiler that optimizes redundant code is sadly new feature. But still, why have two lines to maintain when you can have one.
var nums = [];
for( var i = 0; i < 18; i++ ) {
nums[i] = parseInt( document.getElementById("spin" + i).value );
}
Don't push, insert
The push method has an expensive overhead so use it with caution.
Loggers
The console has a built in logger, why not use that instead of an alert box?
console.log( nums.length );
try this
var nums = [];
for(var i = 1; i <= 18; i++){
var num= parseInt(document.getElementById("spin" + i).value);
nums.push(num);
}
alert(nums.length);
A couple of things to note:
As PSR has mentioned, you use:
var num[i]
when it should be
var num
getElementById(id).value only works for form elements, you have to use .innerHTML for divs.
This works for me: http://jsfiddle.net/sbqeT/

Javascript record keystroke timings

I want to record the time between each keystroke (just one key to start with, the 'A' key) in millseconds.
After the user finishes his thing he can submit and check out the timings between each key stroke. Like:
1: 500
2: 300
3: 400
4: 500
5: 100
6: 50
7: 50
8: 25
I believe this is possible with Javascript, is it?
Sure:
var times = [];
// add an object with keycode and timestamp
$(document).keyup(function(evt) {
times.push({"timestamp":evt.timeStamp,
"keycode":evt.which})
});
// call this to get the string
function reportTimes() {
var reportString = "";
for(var i = 0; i < times.length - 1; ++i) {
reportString += (i+1) + ": " + (times[i+1].timestamp - times[i].timestamp) + " ";
}
return reportString; // add this somewhere or alert it
}
I added the keycode just in case you wanted it later; it's not necessary for your exact problem statement.
Clarification from comments discussion:
The for loop only goes to up to times.length - 2 (since i is always strictly less than times.length - 1), so there is no issue about times[i+1] being outside the bounds of the array. For example, if you do five key presses and therefore have a times array with five elements (indexed from 0 to 4):
1st pass: times[1].timestamp - times[0].timestamp
2nd pass: times[2].timestamp - times[1].timestamp
3rd pass: times[3].timestamp - times[2].timestamp
4th pass: times[4].timestamp - times[3].timestamp
Then the loop terminates, because setting i to 4 triggers the termination condition:
= i < times.length - 1
= 4 < 5 - 1
= 4 < 4
= false [i cannot be set to 4 by this loop]
Thus, times[i+1] is always a validly indexed element, because i is at most one less than the maximum index.

Categories

Resources