Javascript comma between seconds - javascript

I'm trying to fix this but I can't figure out where I need to start. I using an timer for a banner to play a game and the timer is in seconds with 4 digits. Now, I would like to have a comma between the seconds so it look like this: 13,80 instead of this: 1380. How can I make sure there will be a comma in the seconds?
Here is my code:
var x = new clsStopwatch();
var $time;
var clocktimer;
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
var s = ms = 0;
var newTime = '';
time = time % (60 * 60 * 1000);
m = Math.floor( time / (60 * 1000) );
time = time % (24 * 1000);
s = Math.floor( time / 45 + 3800);
newTime = pad(s,4) ;
return newTime;

Use like this:
var str = 1234;
console.log(str.substr(0,2)+','+str.substr(2)); //will print 12,34
Ur code will become:
function pad(num, size) {
var s = "0000" + num;
var str = s.substr(s.length - size);
return str.substr(0,2)+','+str.substr(2);
}

var myNumber = 123;
var myArray = myNumber.toString().split(""); // ["1", "2", "3"]
while (myArray.length < 4) {
myArray.unshift("0"); // ["0", "1", "2", "3"];
}
myArray.splice(2, 0, ","); // second position, take none out, insert comma
// ["0, "1", ",", "2", "3"];
console.log(myArray.join("")); // myArray.join("") === "01,23"

Not the most elegant solution, but it works
//takes a number
//e.g. 9104 returns 91,04
function addComma(number){
var frm = String(number);
return number > 99 ? frm.substring(0, frm.length-2) + ',' + frm.substring(frm.length-2, frm.length) : "0," + frm
}

Related

Problems with when trying to sum time using function in javascript

I have tried several suggestions on how to sum hours and minutes but all have failed to me.
I'm using this script as a start https://olanaso.github.io/Leaflet-Select-Polygons/# and need to have more rows with other totals from selected polygons, one of them is time (h:mm 00:00). Every polygon has properties with hour and minute, some has 00:00. I have manage to add more totals but when it comes to sum the time it has not worked for me. When you select polygons the totals adds up and when deselect a polygon the totals updates with removing that value. This function "timestrToSec" is one I have been trying, but getting the error "time.split is not a function". Also I don't need days just hours and minutes summed together like "300:15 h:mm" (3 hundred hours and 15 minutes) when selecting polygons och deselecting.
$.each(statesData.features, function(index, feature) {
var name = `${feature.properties.ZIPCODE} ${feature.properties.Name} ( ${feature.properties.average_time} - ${feature.properties.CITY})`
placenames.push(name);
zipcodes[name] = feature.properties.ZIPCODE;
time = feature.properties.average_time
});
More....
// Now get the totals of selected polygons
var detailshow = function() {
var result = ''
var total = 0
var total1 = 0
var total2 = 0
for (var i = 0; i < featuresSelected.length; i++) {
var properties = featuresSelected[i].feature.properties
result +=
`
${properties.CITY}<br>
Zipcode: ${properties.ZIPCODE}
<a href="#" onclick=dellayer(${properties.ZIPCODE})>Delete</a>
<hr>`;
total += properties.amount,
total1 += properties.average_time,
total2 += properties.distance
var convertTime = function (input, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
return [
pad(Math.floor(input / 3600)),
pad(Math.floor(input % 3600 / 60)),
pad(Math.floor(input % 60)),
].join(typeof separator !== 'undefined' ? separator : ':' );
}
var resultTime = convertTime(total1);
}
return {
result: result,
total: total,
resultTime: resultTime,
total2: total2
};
}
detailsselected.update = function(arrayselected) {
var details = detailshow()
this._div.innerHTML =
'<b>Zipcodes</b><br>' +
'Total time: <b>' + details.resultTime + ' hh:mm:ss</b><br>' +
'Amount: <b>' + details.total + ' st</b><br>' +
'Distance: <b>' + details.total2.toFixed(1) + ' km</b><br>';
$('#suma', window.parent.document).val(details.total, details.resultTime, details.total2);
};
detailsselected.addTo(map);
This is part of the json file structure:
var statesData = new L.LayerGroup;
var statesData = {"type":"FeatureCollection","features":[{"type":"Feature","properties":{"ZIPCODE":12345,"CITY":"LONDON","REGION":"REGION SOUTH","amount":1088,"average_time":"06:39","distance":2.2},"geometry":{"type":"MultiPolygon","coordinates":...
I didn't really try to follow everything you're doing, but if all you're trying to do is to add together hh:mm times, then something like this should work:
const addTimes = (hhmm1, hhmm2) => {
const [h1, m1] = hhmm1.split(':').map(Number)
const [h2, m2] = hhmm2.split(':').map(Number)
const minutes = 60 * h1 + m1 + 60 * h2 + m2
return `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, '0')}`
}
const addManyTimes = (ts) => ts.reduce(addTimes, '0:00')
console .log (addTimes ('3:41', '7:55')) //=> '11:36'
console .log (addManyTimes (['2:12', '3:07', '8:39', '6:21', '5:59'])) //=> '26:18'
It would be easy enough to extend this to seconds as well if that were necessary.

How can I count the number of zero decimals in JavaScript?

How do I get the number of zero decimals behind the comma (but not the total)? So to illustrate an example:
0.00001 > 4
0.000015 > 4
0.0000105 > 4
0.001 > 2
I am looking for methods that are efficient (meaning that they optimize the calculation time).
You can use logarithms to find the magnitude of the number:
var x = 0.00195;
var m = -Math.floor( Math.log(x) / Math.log(10) + 1);
document.write(m); // outputs 2
Later versions of JavaScript have Math.log10, so it would be:
var x = 0.00195;
var m = -Math.floor( Math.log10(x) + 1);
document.write(m); // outputs 2
How using the base-10 logarithm of the numbers works:
x
Math.log10(x)
Math.floor(Math.log10(x) + 1 )
0.1
-1
0
0.01
-2
-1
0.015
-1.8239…
-1
0.001
-3
-2
0.00001
-5
-4
0.000015
-4.8239…
-4
0.0000105
-4.9788…
-4
Use a regex to match the number of zeros after a decimal point and then count them.
var zeros = float.toString().match(/(\.0*)/)[0].length - 1;
DEMO
Use this one:
function numberOfZeros(n) {
var c = 0;
while (!~~n) {
c++;
n *= 10;
}
return c - 1;
}
document.write(numberOfZeros(0.00065));
This code does the following: it multiplies the number by ten as long as it can be truncated to something not equal 0. The truncation operator "~~" is very performant, because it works with byte representation of the number directly.
It doesn't use any string operations and does exactly what you want: counts the zeros.
//my answer
function t1()
{
var num = 0.0000005323;
numOfZeroes = 0;
while(num < 1)
{
numOfZeroes++;
num *= 10;
}
}
//others
//Andrew Morton's answer
//https://stackoverflow.com/a/31002148/1115360
function t2()
{
var num = 0.0000005323;
var m = -Math.floor( Math.log10(num) + 1);
}
//Amy's Answer
//https://stackoverflow.com/a/31002087/4801298
function t3()
{
var r = 0.0000005323;
var count=0;
var splited = r.toString().split(".")[1];
for(var i=0;i<splited.length;i++)
{
if(splited[i]==0)
{
count++;
}
else
{
break;
}
}
}
//Ted's Answer
//https://stackoverflow.com/a/31002052/4801298
function t4()
{
var number = 0.0000005323;
var numberAsString = number.toString();
var decimalsAsString = numberAsString.substr(numberAsString.lastIndexOf('.')+1);
var leadingZeros = decimalsAsString.substr(0, decimalsAsString.lastIndexOf('0')+1).length;
}
//Bartłomiej Zalewski's answer
//https://stackoverflow.com/a/31001998/4801298
function t5()
{
var n = 0.0000005323;
var c = 0;
while (!~~n) {
c++;
n *= 10;
}
return c - 1;
}
//Andy 's answer
//https://stackoverflow.com/a/31002135/4801298
function t6()
{
var float = 0.0000005323;
var zeros = float.toString().match(/(\.0*)/)[0].length - 1;
}
//Praveen's answer
//https://stackoverflow.com/a/31002011/4801298
function t7()
{
var a = 0.0000005323;
return (a.toString().replace("0.", "").split("0").length - 1);
}
//benchmark function
function bench(func)
{
var times = new Array();
for(var t = 0; t < 100; t++)
{
var start = performance.now();
for(var i = 0; i < 10000; i++)
{
func();
}
var end = performance.now();
var time = end - start;
times.push(time);
}
var total = 0.0;
for(var i=0, l=times.length; i<l; i++)
total += times[i];
var avg = total / times.length;
return avg;
}
document.write('t1: ' + bench(t1) + "ms<BR>");
document.write('t2: ' + bench(t2) + "ms<BR>");
document.write('t3: ' + bench(t3) + "ms<BR>");
document.write('t4: ' + bench(t4) + "ms<BR>");
document.write('t5: ' + bench(t5) + "ms<BR>");
document.write('t6: ' + bench(t6) + "ms<BR>");
document.write('t7: ' + bench(t7) + "ms<BR>");
Note:
This would only work with numbers less than 1 of course. Otherwise, just remove numbers left of the decimal point first, like
num -= num % 1;
need to compare this to another way.
a while later...
I would like a better way to bench these function though. I might have my calculation wrong. I'm adding other peoples answers into the test. I'm now attempting to use the performance API
a bit later than before
AHA! Got it working. Here are some comparisons for you.
You can use something like this:
function num (a) {
return (a.toString().replace("0.", "").split("0").length - 1)
}
Here is a working example (a bit lengthy for clarity):
var number = 0.0004342;
var numberAsString = number.toString();
var decimalsAsString = numberAsString.substr(numberAsString.lastIndexOf('.')+1);
var leadingZeros = decimalsAsString.substr(0, decimalsAsString.lastIndexOf('0')+1).length;
// leadingZeros == 3
Convert the number in to a string and split it with the dot (.). Using the for loop to count the zeros occurrences.
var r = 0.0000107;
var count=0;
var splited = r.toString().split(".")[1];
for(var i=0;i<splited.length;i++)
{
if(splited[i]==0)
{
count++;
}
else
{
break;
}
}
console.log(count);
Node.js 9.0.0
I was looking for a solution without converting or the O(n) approach. Here is what solution I made by O(1).
Part of finding decimal by log – caught from #AndrewMorton, but it might be laggy with the divider: log(10) – 2.302585092994046.
Example
const normalize = (value, zeroCount) => {
const total = 10 ** zeroCount
const zeros = Math.floor(-Math.log10(value / total))
return value * (10 ** zeros)
}
Usage
normalize(1510869600, 13) // 1510869600000
normalize(1510869600, 10) // 1510869600

generate 4 digit random number using substring

I am trying to execute below code:
var a = Math.floor(100000 + Math.random() * 900000);
a = a.substring(-2);
I am getting error like undefined is not a function at line 2, but when I try to do alert(a), it has something. What is wrong here?
That's because a is a number, not a string. What you probably want to do is something like this:
var val = Math.floor(1000 + Math.random() * 9000);
console.log(val);
Math.random() will generate a floating point number in the range [0, 1) (this is not a typo, it is standard mathematical notation to show that 1 is excluded from the range).
Multiplying by 9000 results in a range of [0, 9000).
Adding 1000 results in a range of [1000, 10000).
Flooring chops off the decimal value to give you an integer. Note that it does not round.
General Case
If you want to generate an integer in the range [x, y), you can use the following code:
Math.floor(x + (y - x) * Math.random());
This will generate 4-digit random number (0000-9999) using substring:
var seq = (Math.floor(Math.random() * 10000) + 10000).toString().substring(1);
console.log(seq);
I adapted Balajis to make it immutable and functional.
Because this doesn't use math you can use alphanumeric, emojis, very long pins etc
const getRandomPin = (chars, len)=>[...Array(len)].map(
(i)=>chars[Math.floor(Math.random()*chars.length)]
).join('');
//use it like this
getRandomPin('0123456789',4);
$( document ).ready(function() {
var a = Math.floor(100000 + Math.random() * 900000);
a = String(a);
a = a.substring(0,4);
alert( "valor:" +a );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Your a is a number. To be able to use the substring function, it has to be a string first, try
var a = (Math.floor(100000 + Math.random() * 900000)).toString();
a = a.substring(-2);
You can get 4-digit this way .substring(startIndex, length), which would be in your case .substring(0, 4). To be able to use .substring() you will need to convert a to string by using .toString(). At the end, you can convert the resulting output into integer by using parseInt :
var a = Math.floor(100000 + Math.random() * 900000)
a = a.toString().substring(0, 4);
a = parseInt(a);
alert(a);
https://jsfiddle.net/v7dswkjf/
The problem is that a is a number. You cannot apply substring to a number so you have to convert the number to a string and then apply the function.
DEMO: https://jsfiddle.net/L0dba54m/
var a = Math.floor(100000 + Math.random() * 900000);
a = a.toString();
a = a.substring(-2);
$(document).ready(function() {
var a = Math.floor((Math.random() * 9999) + 999);
a = String(a);
a = a.substring(0, 4);
});
// It Will Generate Random 5 digit Number & Char
const char = '1234567890abcdefghijklmnopqrstuvwxyz'; //Random Generate Every Time From This Given Char
const length = 5;
let randomvalue = '';
for ( let i = 0; i < length; i++) {
const value = Math.floor(Math.random() * char.length);
randomvalue += char.substring(value, value + 1).toUpperCase();
}
console.log(randomvalue);
function getPin() {
let pin = Math.round(Math.random() * 10000);
let pinStr = pin + '';
// make sure that number is 4 digit
if (pinStr.length == 4) {
return pinStr;
} else {
return getPin();
}
}
let number = getPin();
Just pass Length of to number that need to be generated
await this.randomInteger(4);
async randomInteger(number) {
let length = parseInt(number);
let string:string = number.toString();
let min = 1* parseInt( string.padEnd(length,"0") ) ;
let max = parseInt( string.padEnd(length,"9") );
return Math.floor(
Math.random() * (max - min + 1) + min
)
}
I've created this function where you can defined the size of the OTP(One Time Password):
generateOtp = function (size) {
const zeros = '0'.repeat(size - 1);
const x = parseFloat('1' + zeros);
const y = parseFloat('9' + zeros);
const confirmationCode = String(Math.floor(x + Math.random() * y));
return confirmationCode;
}
How to use:
generateOtp(4)
generateOtp(5)
To avoid overflow, you can validate the size parameter to your case.
Numbers don't have substring method. For example:
let txt = "123456"; // Works, Cause that's a string.
let num = 123456; // Won't Work, Cause that's a number..
// let res = txt.substring(0, 3); // Works: 123
let res = num.substring(0, 3); // Throws Uncaught TypeError.
console.log(res); // Error
For Generating random 4 digit number, you can utilize Math.random()
For Example:
let randNum = (1000 + Math.random() * 9000).toFixed(0);
console.log(randNum);
This is quite simple
const arr = ["one", "Two", "Three"]
const randomNum = arr[Math.floor(Math.random() * arr.length)];
export const createOtp = (): number => {
Number(Math.floor(1000 + Math.random() * 9000).toString());
}

Generate incremented random numbers between 0 to 100 every second where new number should be greater than the previous nymber

I need a javascript where with every second call i get a random number between 0-100 where current number should be greater than previous number. I wrote a code to get random numbers every second but stuck at generating it with increment.
<script>
var span = document.getElementsByTagName("span")[3];
var i = 100;
(function randNumber() {
var a = Math.floor((Math.random() * i) + 1);
span.innerHTML = "RandNumber: " + a;
setTimeout( randNumber, 1000);
})();
Note : The numbers should generate randomly.
example result may be : 2,5,7,8,22,23,34,56,78,88.....
You should not create a new random number between zero and your maximum (i), but just between the last created number (lastNumber) and max (i).
Also you might want to stop, when the random numbers reached the maximum.
var span = document.getElementsByTagName("span")[3],
i = 100,
lastNumber = 0;
function randNumber() {
lastNumber = lastNumber + Math.floor( Math.random() * (i - lastNumber) + 1 );
span.innerHTML = lastNumber;
if( lastNumber < i ) {
setTimeout( randNumber, 1000 );
}
}
randNumber();
AS for the comments and the requirement of a minimum amount of steps until reaching the maximum:
In each iteration, just increase you number by a random value between 1 and ((max - min) / steps. It is pretty much the same code as above.
var span = document.getElementsByTagName("span")[3],
max = 100,
min = 0,
lastNumber = 0,
minSteps = 30;
// how wide can the average step be at most?
var stepWidth = (max - min) / minSteps;
function randNumber() {
lastNumber = lastNumber + Math.floor( Math.random() * stepWidth + 1 );
span.innerHTML = lastNumber;
if( lastNumber < max ) {
setTimeout( randNumber, 1000 );
}
}
randNumber();
If you extract the "between two numbers" logic into its own function like this, this becomes a lot easier. This way, you just generate a number between your last generated number and your maximum.
var max = 100
var last_number = 1
var interval_id = setInterval(function(){
last_number = get_random_number_greater_between(last_number, max)
span.innerHTML = "RandNumber: " + last_number;
if(last_number >= max){
window.clearInterval(interval_id)
}
}, 1000)
function get_random_number_greater_between(low, high){
return Math.floor(Math.random() * (high - low + 1) + low);
}
Try this:
// generate a random number from 0 to max - 1.
function rand(max) {
return Math.floor(max * Math.random());
}
// generate a random number from min to max.
function range(min, max) {
return min + rand(1 + max - min);
}
// the loop function
function next(n, callback) {
var m = range(n, 100);
if (m < 100) setTimeout(next, 1000, m + 1, callback);
callback(m);
}
var span = document.getElementById("rand");
next(0, function (m) {
span.innerHTML = "Random number: " + m;
});
<span id="rand"></span>

image based count down clock

I have a count down clock which works absolutely fine. Now the question is can I display images as digits instead of html. I cant seem to figure out the logic how would I approach it. I really dont want to use a plugin for this so that is really not an option.
and the JS for the clock is this
setInterval(function(){
var future = new Date("Jan 20 2014 21:15:00 GMT+0200");
var now = new Date();
var difference = Math.floor((future.getTime() - now.getTime()) / 1000);
var seconds = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
var minutes = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
var hours = fixIntegers(difference % 24);
difference = Math.floor(difference / 24);
var days = difference;
$(".seconds").text(seconds + "s");
$(".minutes").text(minutes + "m");
$(".hours").text(hours + "h");
$(".days").text(days + "d");
}, 1000);
function fixIntegers(integer)
{
if (integer < 0)
integer = 0;
if (integer < 10)
return "0" + integer;
return "" + integer;
}
I have stored the images in an array which is this
var linkCons = 'http://soumghosh.com/otherProjects/Numbers/'
var num = [];
var linkCons = "http://soumghosh.com/otherProjects/Numbers/";
for(var i = 0; i < 10; i++) {
num.push(linkCons + "nw" + i + ".png");
}
Thanks to stack overflow folks helping me cleaning the array. Really appriciate it
And here is the working fiddle
http://jsfiddle.net/sghoush1/wvbPq/3/
You can do it using only one sprite image and this bit of code I created:
jQuery(function($) { // DOM ready shorthand
// CLOCK
// Just a date in the future... Say 5 days from now
var fut = new Date().setDate(new Date().getDate() + 5);
// Number splitter
function intSpl(i) {
i = Math.floor(i);
return [Math.floor(i / 10), i % 10]; // 37=[3,7] // 5=[0,5] // 0=[0,0]
}
var obj = {}; // {d:[7,7], h:[1,9], .....}
function drawTime() {
var now = new Date().getTime();
var dif = now < fut ? Math.floor((fut - now) / 1000) : 0;
obj.s = intSpl(dif % 60);
obj.m = intSpl(dif / 60 % 60);
obj.h = intSpl(dif / 60 / 60 % 24);
obj.d = intSpl(dif / 60 / 60 / 24);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
for (var i = 0; i < 2; i++) { // get el ID number (0,1)
$('#' + key + i).css({
backgroundPosition: -obj[key][i] * 50
});
}
}
}
}
drawTime();
setInterval(drawTime, 1000);
});
#clock span {
display: inline-block;
width: 50px;
height: 85px;
background: url('http://i.imgur.com/uBTxTTD.jpg');
background-position: 0 0;
}
#clock span:nth-child(even) {
margin-right: 15px;
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<div id="clock">
<span id="d0"></span>
<span id="d1"></span>
<span id="h0"></span>
<span id="h1"></span>
<span id="m0"></span>
<span id="m1"></span>
<span id="s0"></span>
<span id="s1"></span>
</div>
To explain the idea:
Create elements, each will hold a one digit of the current 2 digits value;
Set a common bg image to all spans in CSS
Every second move each element's background-image left by -(witdh * number) px
While the listed above seems logic, the first problem you can see here is how to retrieve separately a JS time number (1 or 2 digits) keep leading zero if needed, and reference each digit to target the right element in HTML?
Let's start by splitting numbers:
35 == 3, 5 /// 0 == 0, 0 // this is an example of what we need.
var n = 35; // Set any 1 or 2 digit number.
var n1 = ~~(n/10); // 3 //// ~~ "Double Bitwise NOT"
// just instead of parseInt(time/10, 10).
var n2 = n%10; // 5 //// % "Mudulus operator" (reminder).
Example playground
JS Grouping
Now, how to group this two separated digits and say: "Hey you two are for my clock seconds!" ?
By simply putting them into an array! [3, 5], and for we'll have also minutes, hours and day - let's simply put all those arrays into an Object and assign a Key Name which will result in having an object like:
obj = {d:[7,4], h:[1,9], m:[2,9], s:[0,7]}
Reference to HTML
Having that Object and knowing that inside an for...in loop we can retrieve the Key name and the array value like eg: obj['d'][0] === 7 obj['d'][5] === 4
means that we'll need a for loop to retrieve the 0 and 1 to get the values in our array positions [pos0, pos1]
all inside a for...in loop that will get the KEY names : d, h, m, s
2pos x 4keyNames = 8 elements iterations/second
means that now we'll be able to target an ID element eg: #s0 and #s1
and all we need now is to retrieve the value and animate that element background by
-width * digit
Well, there's another way that you may use to solve the same problem. Here are the steps. Firstly I wrote one CSS class selector for each image position.
.list-group-item .digit-display{
display:inline-block;
width:50px;
height:85px;
background:url('http://i.imgur.com/uBTxTTD.jpg');
}
.position-0 {
background-position: 0 0;
}
.position-1 {
background-position: -50px 0px !important;
}
Then I wrote a JavaScript function which takes a digit as an input and return the CSS class selector for that digit as below.
displayDigit(digit) {
const baseSelector = "digit-display position-";
return `${baseSelector}${digit}`;
}
Finally this function is called inside the JSX element as below.
<span className = {this.displayDigit(remainingTime["h"].charAt(0))}></span>
That solved the issue.
However, if someone really needs to go with the jquery based approach specified above, we can still condense down that same code as below.
secondsToTime(secs) {
let hours = `${constants.ZERO}${Math.floor(secs / (60 * 60))}`.slice(-2);
let divisorForMinutes = secs % (60 * 60);
let minutes = `${constants.ZERO}${Math.floor(divisorForMinutes / 60)}`.slice(-2);
let divisorForSeconds = divisorForMinutes % 60;
let seconds = `${constants.ZERO}${Math.ceil(divisorForSeconds)}`.slice(-2);
let obj = {
"h": hours,
"m": minutes,
"s": seconds
};
return obj;
}
handleFlipClockImage = () => {
var myObj = this.secondsToTime(seconds);
Object.keys(myObj).forEach(key => {
let obj = myObj[key];
var digits = obj.split(constants.EMPTY_SPACE_CHAR);
digits.forEach((digit, index) => {
jquery(`#${this.state.label}${key}${index}`).css({backgroundPosition: -digit*50 });
});
});
}

Categories