How do I remove "undefined" from the beginning of JavaScript array items? - javascript

I'm trying to generate an array of random digits, but I'm getting "undefined" at the beginning of each row. I've been searching online for a couple of hours, but haven't been able to figure it out.
The expected output should be 5 rows of 2 random digits like this:
87
57
81
80
02
but the actual output looks like this:
undefined87
undefined57
undefined81
undefined80
undefined02
This is a modified excerpt that produces the result shown above:
function NumberSet() {
// generate all the digits
this.generate = function() {
random_digits = [];
// create 5 rows of 2 random digits
for(i=0; i<5; i++) {
for(z=0; z<2; z++) {
// use .toString() in order to concatenate digits to
// the array without adding them together
random_digit = Math.floor(Math.random()*10).toString();
random_digits[i] +=random_digit;
}
}
return random_digits;
}
}
randomnumbers1 = new NumberSet();
mynums = randomnumbers1.generate();
jQuery.each(mynums, function(i, l) {
// display output in a div#nums
$('#nums').append(l + '<br>');
});
The final version won't be using this method to display the digits. I'm just trying to troubleshoot where the "undefined" is coming from.

Initialize your variables
random_digits[i] = "";
for(z=0; z<2; z++) {
random_digit = Math.floor(Math.random()*10).toString();
random_digits[i] +=random_digit;
}
Declare the variables properly with var.
var random_digit, random_digits = [];

Declare random_digit in the first for loop and assign an empty string.
Go through the inner for loop appending your random numbers, and then push() to the array back in the outer for loop.
function NumberSet() {
// generate all the digits -a meme should be attached here-
this.generate = function() {
random_digits = [];
// create 5 rows of 2 random digits
for(i=0; i<5; i++) {
var random_digit = ""; //Declare it out here
for(z=0; z<2; z++) {
// use .toString() in order to concatenate digits to
// the array without adding them together
random_digit += Math.floor(Math.random()*10).toString(); //Append it here
}
random_digits.push(random_digit); //Push it back here
}
return random_digits;
}
}
Fiddle-dee-dee
OR Forget the inner loop and use recursion
function NumberSet() {
// generate all the digits
this.generate = function () {
random_digits = [];
// create 5 rows of 2 random digits
// Use i for how many numbers you want returned!
var random_digit = function (i) {
var getRand = function() {
return (Math.floor(Math.random() * 10).toString());
}
return (i > 0) ? getRand()+random_digit(i-1) : "";
};
for (i = 0; i < 5; i++) {
random_digits.push(random_digit(2)); //In this case, you want 2 numbers
}
return random_digits;
}
}
Fiddle-do-do
And the final version because I'm bored
function NumberSet(elNum, numLen) {
this.random_digits = []; //Random digits array
this.elNum = elNum; //Number of elements to add to the array
this.numLen = numLen; //Length of each element in the array
// generate all the digits
this.generate = function () {
// create 5 rows of 2 random digits
var random_digit = function (i) {
var getRand = function () {
return (Math.floor(Math.random() * 10).toString());
}
return (i > 0) ? getRand() + random_digit(i - 1) : "";
};
for (i = 0; i < this.elNum; i++) {
this.random_digits.push(random_digit(this.numLen));
}
return this.random_digits;
}
}
randomnumbers1 = new NumberSet(5, 2).generate();
jQuery.each(randomnumbers1, function (i, l) {
// display output in a div#nums
$('#nums').append(l + '<br>');
});
Fiddle on the roof

Replace
random_digits[i] +=random_digit;
With
random_digits[i] = (random_digits[i] == undefined ? '' : random_digits[i]) + random_digit;
Demo: Fiddle

Your function can be simplified to:
function NumberSet() {
this.generate = function() {
var random_digits = new Array();
for (i = 0; i < 5; i++) {
randnum = Math.floor(Math.random() * 99);
random_digits[i] = (randnum < 10 ? '0' : 0) + randnum;
}
return random_digits;
}
}
Live Demo

Related

How do I return only the letter that repeats the most times?

How do I return only the letter that repeats the most times? How to make it return only the result e = 5 in the following case
enter code here
var s = "Teeeeessttt"
var x = (s.toLowerCase());
function count() {
array_elements = ([...x]);;
array_elements.sort();
var current = null;
var cnt = 0;
for (var i = 0; i < array_elements.length; i++) {
if (array_elements[i] != current) {
if (cnt > 0) {
document.write(current + ' - ' + cnt + '<br>');
}
current = array_elements[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
document.write(current + ' - ' + cnt);
}
}
count();
First you would need to count the amount of times a character occurs. You could use the reduce method to loop over each character and store that character as a key in an object. The value of the key should represent the amount of times the character has occurred.
It would look like the object below.
{
"t": 4,
"e": 5,
"s": 2
}
From here you want to look for the highest number and return the key that corresponds to it. I've borrowed the solution of this SO thread to get the highest count of the object using another reduce loop.
const string = "Teeeeessttt";
const mostOccuringCharacter = string => {
// Count the occurence of each character.
const count = [...string.toLowerCase()].reduce((counter, char) => {
counter[char] = (counter[char] || 0) + 1;
return counter;
}, {});
// Compare the values with each other and return the
// character with the highest count.
const highestChar = Object.keys(count).reduce((a, b) =>
count[a] > count[b] ? a : b);
// Return an array with the character and the count.
return [highestChar, count[highestChar]]
};
const [ char, count ] = mostOccuringCharacter(string);
console.log(`${char} = ${count}`);
#UKS points out a dupe for this, interestingly there was a post with issues with funcky unicode.. eg. πŸ‘¦πŸΏπŸ‘¦πŸ‘¦πŸΏπŸ‘¦πŸ‘¦πŸ»πŸ‘¦πŸ½πŸ‘¦πŸΎπŸ‘¦πŸΏ, but no solution was shown for this.
So with that in mind I thought I would knock up a version that handles unicode nicely. I've also split into multiple functions for re-use. As you can see it's also easy to alter to find the least used character if so wanted. Not sure if this will handle 100% unicode, there might be some even more funcky ones. :)
function unicodeStrSplit(str) {
const x = [...str];
//let handle some funcky unicode
for (let p=x.length-1;p>0;p--)
if(x[p].charCodeAt(0)===0xd83c){x[p-1] += x[p], x.splice(p, 1) };
return x;
}
function arrayCounter(arr) {
return [...arr.reduce((a,v)=>a.set(v,a.get(v)+1||1),new Map())].
sort((a,b) => b[1]-a[1]);
}
function stringCounter(str) {
return arrayCounter(unicodeStrSplit(str));
}
console.log(stringCounter("Teeeeessttt").shift()); //first array item
//funcky unicode too.
console.log(stringCounter('πŸ‘¦πŸΏπŸ‘¦πŸ‘¦πŸΏπŸ‘¦πŸ‘¦πŸ»πŸ‘¦πŸ½πŸ‘¦πŸΎπŸ‘¦πŸΏ').shift()); //first array item
//also let's get the least used
console.log(stringCounter('πŸ‘¦πŸΏπŸ‘¦πŸ‘¦πŸΏπŸ‘¦πŸ‘¦πŸ»πŸ‘¦πŸ½πŸ‘¦πŸΎπŸ‘¦πŸΏ').pop()); //last array item

How do I fix this code? It's use 3 seperate functions one to add to the array, one to sort and one to display. Javascript

I'm doing a question that asks: Read 10 numbers and print the biggest number from the list of reading numbers. Make use of Array and Functions.
One Function to read the integer numbers and another function to print the biggest number from the list.
I'm having trouble with getting the biggest number and returning it back to the code so that I can display it. I've messed around with it allot so it might not make as much sense right now (I'm sorry).
I've been stuck on it forever any help would be much appreciated :).
var numbers = [];
var BiggestNumber = 0;
BigestNumber = BiggestSort(numbers);
numbers = ReadNumbers();
Display(BiggestNumber)
function ReadNumbers() {
var ArgNumbers = [];
var ArgInput;
var ctr;
for (ctr = 0; ctr < 3; ctr++) {
ArgInput = parseFloat(prompt("Please enter a number: "));
ArgNumbers.push(ArgInput);
}
return ArgNumbers;
}
function BiggestSort(ArgNumber) {
var ArgNumber = [];
var ArgBiggest = 0;
var ctr;
for (ctr = 0; ctr < 3; ctr++)
if (ArgNumber[ctr] > ArgBiggest) {
ArgBiggest = ArgNumber[ctr];
}
return ArgBiggest;
}
function Display(ArgNumber) {
alert("The biggest number was: " + ArgNumber);
}
I've added a snippet at the end that demonstrates how I might do such a thing from scratch, but let's look at your code first:
From the top:
There's no need to declare numbers and BiggestNumber with initial values and then immediately reassign them. Declare them at assignment time:
// var numbers = [];
// var BiggestNumber = 0;
const BigestNumber = BiggestSort(numbers);
const numbers = ReadNumbers();
There's a typo in BigestNumber (missing second 'g'):
// const BigestNumber = BiggestSort(numbers);
const BiggestNumber = BiggestSort(numbers);
const numbers = ReadNumbers();
You're calling BiggestSort(numbers) before numbers has a meaningful value. Call ReadNumbers() first to initialize numbers, then pass it to BiggestSort:
// const BiggestNumber = BiggestSort(numbers);
// const numbers = ReadNumbers();
const numbers = ReadNumbers();
const BiggestNumber = BiggestSort(numbers);
Again, no need to declare ArgInput and ctr separately. It doesn't really hurt anything, but it's unnecessary:
function ReadNumbers() {
const ArgNumbers = [];
// var ArgInput;
// var ctr;
for (let ctr = 0; ctr < 3; ctr++) {
const ArgInput = parseFloat(prompt("Please enter a number: "));
ArgNumbers.push(ArgInput);
}
return ArgNumbers;
}
You're receiving an ArgNumber parameter, and then declaring another variable with the same name. Use the argument passed in.
Because the ArgNumber parameter is an array, you can use its length property in the loop condition instead of hard-coding 3.
You're missing curly braces around your loop body.
function BiggestSort(ArgNumber) {
// var ArgNumber = [];
let ArgBiggest = 0;
// var ctr;
// for (ctr = 0; ctr < 3; ctr++)
for (let ctr = 0; ctr < ArgNumber.length; ctr++) { // added curly brace
if (ArgNumber[ctr] > ArgBiggest) {
ArgBiggest = ArgNumber[ctr];
}
} // added closing brace
return ArgBiggest;
}
With the changes described above, it works:
const numbers = ReadNumbers();
const BiggestNumber = BiggestSort(numbers);
Display(BiggestNumber);
function ReadNumbers() {
const ArgNumbers = [];
for (let ctr = 0; ctr < 3; ctr++) {
const ArgInput = parseFloat(prompt("Please enter a number: "));
ArgNumbers.push(ArgInput);
}
return ArgNumbers;
}
function BiggestSort(ArgNumber) {
let ArgBiggest = 0;
for (let ctr = 0; ctr < ArgNumber.length; ctr++) {
if (ArgNumber[ctr] > ArgBiggest) {
ArgBiggest = ArgNumber[ctr];
}
}
return ArgBiggest;
}
function Display(ArgNumber) {
alert("The biggest number was: " + ArgNumber);
}
Consider this approach:
// A function to prompt for a series of numbers:
// The 'count' parameter is how many numbers to prompt for.
// The 'previous' parameter is an array of the numbers already entered, initally empty.
function readNumbers (count, previous = []) {
// if count is zero, we're done. return the already entered numbers.
if (count === 0) {
return previous;
}
// prompt for the next number
const number = parseFloat(prompt('Enter a number: '));
// push the new number onto the end of the list
previous.push(number);
// call readNumbers again, subtracting one from 'count'
// and return whatever it returns.
return readNumbers(count - 1, previous);
}
// invoke readNumbers to prompt the user.
const numbers = readNumbers(3);
// use Math.max to find the largest number
const largest = Math.max(...numbers);
// show the result
alert(`The biggest number was ${largest}`);
Correct typos like BigestNumber and BiggestNumber.
do ReadNumbers before BiggestSort method call.
remove\avoid reassigning to parameters\args you pass into method scopes, i.e. ArgNumber in the BiggestSort method.
var numbers = [];
numbers = ReadNumbers(3);
BiggestNumber = BiggestSort(numbers);
Display(BiggestNumber)
function ReadNumbers(numberToRead) {
var ArgNumbers = [];
var ArgInput;
for (var ctr = 0; ctr < numberToRead; ctr++) {
ArgInput = parseFloat(prompt("Please enter a number: "));
ArgNumbers.push(ArgInput);
}
return ArgNumbers;
}
function BiggestSort(ArgNumber) {
var ArgBiggest = 0;
for (var ctr = 0, max = ArgNumber.length; ctr < max; ctr++)
if (ArgNumber[ctr] > ArgBiggest) {
ArgBiggest = ArgNumber[ctr];
}
return ArgBiggest;
}
function Display(ArgNumber) {
alert("The biggest number was: " + ArgNumber);
}
I also passed in the number of loops (numberToRead) and ensure the loop in BiggestSort uses the length of the passed array (ArgNumber).

Removing zeros after comma based on maximum consequent zeros

I have a page with a grid where user's numbers get saved. It has a following pattern - every number ends with 3 digits after comma. It doesn't look nice, when for example user's input is
123,450
123,670
123,890
It's much better to have just 2 numbers after comma, because last 0 is absolutely meaningless and redundant.
The way it still should have 3 digits is only if at least one element in an array doesn't end up with 0
For example:
123,455
123,450
123,560
In this case 1st element of the array has the last digit not equal to 0 and hence all the elements should have 3 digits. The same story with 2 or 1 zeros
Zeros are redundant:
123,30
123,40
123,50
Zeros are necessary:
123,35
123,40
123,50
The question is how can I implement it programatically? I've started like this:
var zeros2Remove = 0;
numInArray.forEach(function(item, index, numInArray)
{
var threeDigitsAfterComma = item.substring(item.indexOf(',') + 1);
for(var j = 2; j <= 0; j--)
{
if(threeDigitsAfterComma[j] == 0)
{
zeros2Remove =+ 1;
}
else //have no idea what to do..
}
})
Well in my implementation I don't know how to do it since I have to iterate through every element but break it if at least 1 number has a last digit equal to zero.. In order to do that I have to break outer loop, but don't know how and I'm absolutely sure that I don't have to...
I think the following code what you are looking for exactly , please manipulate numbers and see the changes :
var arr = ["111.3030", "2232.0022", "3.001000", "4","558.0200","55.00003000000"];
var map = arr.map(function(a) {
if (a % 1 === 0) {
var res = "1";
} else {
var lastNumman = a.toString().split('').pop();
if (lastNumman == 0) {
var m = parseFloat(a);
var res = (m + "").split(".")[1].length;
} else {
var m = a.split(".")[1].length;
var res = m;
}
}
return res;
})
var maxNum = map.reduce(function(a, b) {
return Math.max(a, b);
});
arr.forEach(function(el) {
console.log(Number.parseFloat(el).toFixed(maxNum));
});
According to MDN,
There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool. Use a plain loop or for...of instead.
If you convert your forEach loop to a for loop, you can break out of it with a label and break statement:
// unrelated example
let i;
let j;
outerLoop:
for (i = 2; i < 100; ++i) {
innerLoop:
for (j = 2; j < 100; ++j) {
// brute-force prime factorization
if (i * j === 2183) { break outerLoop; }
}
}
console.log(i, j);
I gave you an unrelated example because your problem doesn't need nested loops at all. You can find the number of trailing zeroes in a string with a regular expression:
function getTrailingZeroes (str) {
return str.match(/0{0,2}$/)[0].length;
}
str.match(/0{0,2}$/) finds between 0 and 2 zeroes at the end of str and returns them as a string in a one-element array. The length of that string is the number of characters you can remove from str. You can make one pass over your array of number-strings, breaking out when necessary, and use Array.map as a separate truncation loop:
function getShortenedNumbers (numInArray) {
let zeroesToRemove = Infinity;
for (const str of numInArray) {
let candidate = getTrailingZeroes(str);
zeroesToRemove = Math.min(zeroesToRemove, candidate);
if (zeroesToRemove === 0) break;
}
return numInArray.map(str => str.substring(0, str.length - zeroesToRemove);
}
All together:
function getTrailingZeroes (str) {
return str.match(/0{0,2}$/)[0].length;
}
function getShortenedNumbers (numInArray) {
let zeroesToRemove = Infinity;
for (const str of numInArray) {
let candidate = getTrailingZeroes(str);
zeroesToRemove = Math.min(zeroesToRemove, candidate);
if (zeroesToRemove === 0) break;
}
return numInArray.map(str => str.substring(0, str.length - zeroesToRemove));
}
console.log(getShortenedNumbers(['123,450', '123,670', '123,890']));
console.log(getShortenedNumbers(['123,455', '123,450', '123,560']));
This solution might seem a little cumbersome but it should work for all possible scenarios. It should be easy enough to make always return a minimal number of decimals places/leading zeros.
I hope it helps.
// Define any array
const firstArray = [
'123,4350',
'123,64470',
'123,8112390',
]
const oneOfOfYourArrays = [
'123,30',
'123,40',
'123,50',
]
// Converts 123,45 to 123.45
function stringNumberToFloat(stringNumber) {
return parseFloat(stringNumber.replace(',', '.'))
}
// For 123.45 you get 2
function getNumberOfDecimals(number) {
return number.split('.')[1].length;
}
// This is a hacky way how to remove traling zeros
function removeTralingZeros(stringNumber) {
return stringNumberToFloat(stringNumber).toString()
}
// Sorts numbers in array by number of their decimals
function byNumberOfValidDecimals(a, b) {
const decimalsA = getNumberOfDecimals(a)
const decimalsB = getNumberOfDecimals(b)
return decimalsB - decimalsA
}
// THIS IS THE FINAL SOLUTION
function normalizeDecimalPlaces(targetArray) {
const processedArray = targetArray
.map(removeTralingZeros) // We want to remove trailing zeros
.sort(byNumberOfValidDecimals) // Sort from highest to lowest by number of valid decimals
const maxNumberOfDecimals = processedArray[0].split('.')[1].length
return targetArray.map((stringNumber) => stringNumberToFloat(stringNumber).toFixed(maxNumberOfDecimals))
}
console.log('normalizedFirstArray', normalizeDecimalPlaces(firstArray))
console.log('normalizedOneOfOfYourArrays', normalizeDecimalPlaces(oneOfOfYourArrays))
Try this
function removeZeros(group) {
var maxLength = 0;
var newGroup = [];
for(var x in group) {
var str = group[x].toString().split('.')[1];
if(str.length > maxLength) maxLength = str.length;
}
for(var y in group) {
var str = group[y].toString();
var substr = str.split('.')[1];
if(substr.length < maxLength) {
for(var i = 0; i < (maxLength - substr.length); i++)
str += '0';
}
newGroup.push(str);
}
return newGroup;
}
Try it on jsfiddle: https://jsfiddle.net/32sdvzn1/1/
My script checks the length of every number decimal part, remember that JavaScript removes the last zeros in a decimal number, so 3.10 would be 3.1, so the length is less when there is a number with zeros in the end, in this case we just add a zero to the number.
Update
I've updated the script, the new version adds as much zeros as the different between the max decimal length and the decimal length of the analyzed number.
Example
We have: 3.11, 3.1423, 3.1
The max length would be: 4 (1423)
maxLenght (4) - length of .11 (2) = 2
We add 2 zeros to 3.11, that will become 3.1100
I think you can start out assuming you will remove two extra zeros, and loop through your array looking for digits in the last two places. With the commas, I'm assuming your numArray elements are strings, all starting with the same length.
var numArray = ['123,000', '456,100', '789,110'];
var removeTwo = true, removeOne = true;
for (var i = 0; i < numArray.length; i++) {
if (numArray[i][6] !== '0') { removeTwo = false; removeOne = false; }
if (numArray[i][5] !== '0') { removeTwo = false; }
}
// now loop to do the actual removal
for (var i = 0; i < numArray.length; i++) {
if (removeTwo) {
numArray[i] = numArray[i].substr(0, 5);
} else if (removeOne) {
numArray[i] = numArray[i].substr(0, 6);
}
}

randomly splice values into array

I have an array "A" of scrambled, randomly generated ASCII characters... and a message "M". I want to insert the characters of message M into array A such that the order of M's characters are intact... but randomly distributed throughout array A.
Original array: zH$#%#$##$#^^##(%*$#^&#!$^%&
Sample output: zH$#%#^t$##$#^^h##(%*$#^&#i!$^%&s, etc...
var randomChars = [];
for(var i=33;i<127;++i) {
var letter = document.createElement('span');
letter.innerHTML = String.fromCharCode(i);
randomChars.push(letter);
}
var message = "this is a message";
var rand = 0;
for (var i = 0; i < message.split("").length; i++) {
rand = Math.floor((Math.random() * randomChars.length) + rand);
var letters = document.createElement('span');
letters.innerHTML = message.split("")[i];
letters.setAttribute("hidden","");
randomChars.splice(rand, 0, letters);
}
Fiddle: https://jsfiddle.net/0ftm2srz/1/
Use the previous random index as the minimum (non inclusive) of your next randomly generated index. Start at zero.
You could end up with some barely scrambled stuff, though. (!##!$!#$#!##this) But it's random.
EDIT A better way would be to generate a message.length amount of unique random indices, sort them in ascending, and then insert characters from message at those spots in the scrambled array.
http://jsbin.com/kuzepujabo/1/edit?js,console
var o = {
array: "zH$#%#$##$#^^##(%*$#^&#!$^%&".split(''),
msg: "this is a message",
randomMsgIndex: function () { return Math.floor(Math.random() * this.msg.length); },
randomMsgChar: function () { return this.msg[this.randomMsgIndex()]; },
//resultingArray: [],
randomArrayIndex: function () { return Math.floor(Math.random() * this.array.length); }
}
for(var i = 0; i < o.msg.length; i++) {
o.array.splice(o.randomArrayIndex(), 0, o.randomMsgChar());
}
console.log(o.array);
I have come up with this - but I assume it is still not what you want - you probably want something that keeps track of which message chars were already added - so not to add them twice - and make sure the entire message (all its characters) were added to the array.
Version 2 with the feature described above:
var o = {
array: "zH$#%#$##$#^^##(%*$#^&#!$^%&".split(''),
msg: "this is a message",
msgArray: function () { this.msg.split(''); },
randomMsgIndex: function () { return Math.floor(Math.random() * this.msg.length); },
randomMsgChar: function (i) { return this.msg[i]; },
//resultingArray: [],
randomArrayIndex: function () { return Math.floor(Math.random() * this.array.length); },
stripStr: function (indexToSkip, originalStr) {
var result = "";
for (var i = 0; i < originalStr.length; i++)
if (indexToSkip != i)
result += originalStr[i];
return result;
}
}
for(var i = 0; i < o.msg.length; i++) {
var msgRandomIndex = o.randomMsgIndex();
o.array.splice(o.randomArrayIndex(), 0, o.randomMsgChar(msgRandomIndex));
o.msg = o.stripStr(msgRandomIndex, o.msg);
}
console.log(o.array);
I think it it is still not a 100%, but moving towards the "optimized" solution :-)

Adding commas, decimal to number output javascript

I'm using the following code to count up from a starting number. What I need is to insert commas in the appropriate places (thousands) and put a decimal point in front of the last two digits.
function createCounter(elementId,start,end,totalTime,callback)
{
var jTarget=jQuery("#"+elementId);
var interval=totalTime/(end-start);
var intervalId;
var current=start;
var f=function(){
jTarget.text(current);
if(current==end)
{
clearInterval(intervalId);
if(callback)
{
callback();
}
}
++current;
}
intervalId=setInterval(f,interval);
f();
}
jQuery(document).ready(function(){
createCounter("counter",12714086+'',9999999999,10000000000000,function(){
alert("finished")
})
})
Executed here: http://jsfiddle.net/blackessej/TT8BH/3/
var s = 121221;
Use the function insertDecimalPoints(s.toFixed(2));
and you get 1,212.21
function insertDecimalPoints(s) {
var l = s.length;
var res = ""+s[0];
console.log(res);
for (var i=1;i<l-1;i++)
{
if ((l-i)%3==0)
res+= ",";
res+=s[i];
}
res+=s[l-1];
res = res.replace(',.','.');
return res;
}
Check out this page for explanations on slice(), split(), and substring(), as well as other String Object functions.
var num = 3874923.12 + ''; //converts to a string
numArray = num.split('.'); //numArray[0] = 3874923 | numArray[1] = 12;
commaNumber = '';
i = numArray[0].length;
do
{
//we don't want to start slicing from a negative number. The following line sets sliceStart to 0 if i < 0. Otherwise, sliceStart = i
sliceStart = (i-3 >= 0) ? i-3 : 0;
//we're slicing from the right side of numArray[0] because i = the length of the numArray[0] string.
var setOf3 = numArray[0].slice(sliceStart, i);
commaNumber = setOf3 + ',' + commaNumber; //prepend the new setOf3 in front, along with that comma you want
i -= 3; //decrement i by 3 so that the next iteration of the loop slices the next set of 3 numbers
}
while(i >= 0)
//result at this point: 3,874,923,
//remove the trailing comma
commaNumber = commaNumber.substring(0,commaNumber.length-1);
//add the decimal to the end
commaNumber += '.' + numArray[1];
//voila!
This function can be used for if not working locale somite
number =1000.234;
number=insertDecimalPoints(number.toFixed(3));
function insertDecimalPoints(s) {
console.log(s);
var temaparray = s.split(".");
s = temaparray[0];
var l = s.length;
var res = ""//+s[0];
console.log(res);
for (var i=0;i<l-1;i++)
{
if ((l-i)%3==0 && l>3)
res+= ",";
res+=s[i];
}
res+=s[l-1];
res =res +"."+temaparray[1];
return res;
}
function convertDollar(number) {
var num =parseFloat(number);
var n = num.toFixed(2);
var q =Math.floor(num);
var z=parseFloat((num).toFixed(2)).toLocaleString();
var p=(parseFloat(n)-parseFloat(q)).toFixed(2).toString().replace("0.", ".");
return z+p;
}

Categories