I currently doing formatting of number to currency but is not working on a collection of an array. I used javascript to use the Math.round function. I would like to know how properly use this function. I appreciate your suggestion. Thank you.
Array:
{
"data": [
[
"9812355000",
"23397000",
"13976000"
]
]
}
for (var x = 0; x < data.data.length; x++) {
for (var i0 = 0; i0 < data.data[x].length; i0++) {
dynamicColumn += `<td>${data.data[x][i0] === null || data.data[x][i0] === ""
? 0
: Math.round(data.data[x][i0])}</td>`;
}
}
Need to achieve:
9,812,355,000
23,397,000
13,976,000
To achieve the output you specified using your array, you can iterate though the digits backwards (meaning, starting from the last number and moving to the first number) and then inserting a comma after 3 digits. Some sample code could look like this:
for(let i = numberString.length - 1; i >= 0; i--) {
if (i % 3 === 0)
array.insert(i, ','); // this is not a real function. I leave it up to you to implement this. first param is index and second is what to insert
}
var thousandSeparationRegexp = /\B(?=(\d{3})+(?!\d))/g;
// iterate through numbers
var numberString = number.toString();
var formatted = numberString.replace(thousandSeparationRegexp, ',');
Or inline:
var formatted = number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
You can use an Intl.NumberFormat().format(x):
function myFunction() {
var x = document.getElementById("value_unformated").value
var a = Intl.NumberFormat().format(x)
var text = "Currency format: " + a + "<br>";
document.getElementById("value_formated").innerHTML = text;
}
<input type="number" id="value_unformated" value="13528468">
<button onclick="myFunction()">Format</button>
<p id="value_formated"></p>
Related
I've been trying to use a for loop to make a code that alternates between two strings and ends with .toUpperCase , but I'm completely stuck. I'm "able" to do it with an array with two strings (and even so it has a mistake, as it ends with the first string of the array...), but not with two separate constants.
Could anyone offer some help?
function repeteFrases(num) {
const frases = ["frase um", "frase dois"];
let result = "";
for (let i = 0; i < num; i++) {
result += i === num - 1 ? frases[0].toUpperCase() : `${frases[0]}, ${frases[1]}, `;
}
return result;
}
console.log(repeteFrases(2));
In order to alternate between two states you can use the parity of the index, i.e., the condition would be i % 2 == 0, like this:
function repeteFrases(num) {
const frases = ["frase um", "frase dois"];
let result = "";
for (let i = 0; i < num; i++) {
result += i % 2 == 0 ? frases[0].toUpperCase() : `${frases[0]}, ${frases[1]}, `;
}
return result;
}
console.log(repeteFrases(5));
You've almost got it.. I think what you're asking for is to repeat phrase one or two (alternating), and for the last version to be uppercase. I notice someone else made your code executable, so I might be misunderstanding. We can test odd/even using the modulus operator (%), which keeps the access of frases to either the 0 or 1 position. The other trick is to loop until one less phrase than needed, and append the last one as upper case.
function repeteFrases(num) {
const frases = ["frase um", "frase dois"];
//Only loop to 1 less than the expected number of phrases
const n=num-1;
let result = "";
for (let i = 0; i < n; i++) {
//Note %2 means the result can only be 0 or 1
//Note ', ' is a guess at inter-phrase padding
result+=frases[i%2] + ', ';
}
//Append last as upper case
return result+frases[n%2].toUpperCase();
}
console.log(repeteFrases(2));
console.log(repeteFrases(3));
Use frases[i % frases.length] to alternate the phrases (however many there might be)
function repeteFrases(num) {
const frases = ["frase um", "frase dois"];
let result = "";
for (let i = 0; i < num; i++) {
const next = frases[i % frases.length];
const isLast = (i === num - 1);
result += isLast ? next.toUpperCase() : `${next}, `;
}
return result;
}
console.log(repeteFrases(5));
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);
}
}
I'm working on alternating the case of a string (for example asdfghjkl to AsDfGhJkL).
I tried to do this. I found some code that is supposed to do it, but it doesn't seem to be working.
var str="";
var txt=document.getElementById('input').value;
for (var i=0; i<txt.length; i+2){
str = str.concat(String.fromCharCode(txt.charCodeAt(i).toUpperCase()));
}
Here's a quick function to do it. It makes the entire string lowercase and then iterates through the string with a step of 2 to make every other character uppercase.
var alternateCase = function (s) {
var chars = s.toLowerCase().split("");
for (var i = 0; i < chars.length; i += 2) {
chars[i] = chars[i].toUpperCase();
}
return chars.join("");
};
var txt = "hello world";
console.log(alternateCase(txt));
HeLlO WoRlD
The reason it converts the string to an array is to make the individual characters easier to manipulate (i.e. no need for String.prototype.concat()).
Here an ES6 approach:
function swapCase(text) {
return text.split('').map((c,i) =>
i % 2 == 0 ? c.toLowerCase() : c.toUpperCase()
).join('');
}
console.log(swapCase("test"))
You should iterate the string and alternate between upper-casing the character and lower-casing it:
for (var i=0; i<txt.length; i++) {
var ch = String.fromCharCode(txt.charCodeAt(i);
if (i % 2 == 1) {
ch = ch.toUpperCase();
} else {
ch = ch.toLowerCase();
}
str = str.concat(ch);
}
I'm trying to count the number of times certain words appear in the strings. Every time I run it I get a
uncaught TypeErro: undefined is not a function
I just actually need to count the number of times each "major" appears.
Below is my code:
for(var i = 0; i < sortedarray.length; i++)
{
if(sortedarray.search("Multimedia") === true)
{
multimedia += 1;
}
}
console.log(multimedia);
Here is my csv file which is stored in a 1d array.
"NAME","MAJOR","CLASS STANDING","ENROLLMENT STATUS"
"Smith, John A","Computer Science","Senior","E"
"Johnson, Brenda B","Computer Science","Senior","E"
"Green, Daisy L","Information Technology","Senior","E"
"Wilson, Don A","Information Technology","Junior","W"
"Brown, Jack J","Multimedia","Senior","E"
"Schultz, Doug A","Network Administration","Junior","E"
"Webber, Justin","Business Administration","Senior","E"
"Alexander, Debbie B","Multimedia","Senior","E"
"St. John, Susan G","Information Technology","Junior","D"
"Finklestein, Harold W","Multimedia","Freshman","E"
You need to search inside each string not the array. To only search inside the "Major" column, you can start your loop at index 1 and increment by 4 :
var multimedia = 0;
for(var i = 1; i < sortedarray.length; i += 4)
{
if(sortedarray[i].indexOf("Multimedia") > -1)
{
multimedia += 1;
}
}
console.log(multimedia);
What you're probably trying to do is:
for(var i = 0; i < sortedarray.length; i++)
{
if(sortedarray[i].indexOf("Multimedia") !== -1)
{
multimedia++;
}
}
console.log(multimedia);
I use indexOf since search is a bit of overkill if you're not using regexes.
Also, I replaced the += 1 with ++. It's practically the same.
Here's a more straightforward solution. First you count all the words using reduce, then you can access them with dot notation (or bracket notation if you have a string or dynamic value):
var words = ["NAME","MAJOR","CLASS STANDING","ENROLLMENT STATUS"...]
var count = function(xs) {
return xs.reduce(function(acc, x) {
// If a word already appeared, increment count by one
// otherwise initialize count to one
acc[x] = ++acc[x] || 1
return acc
},{}) // an object to accumulate the results
}
var counted = count(words)
// dot notation
counted.Multimedia //=> 3
// bracket notation
counted['Information Technology'] //=> 3
I don't know exactly that you need this or not. But I think its better to count each word occurrences in single loop like this:
var occurencesOfWords = {};
for(var i = 0; i < sortedarray.length; i++)
{
var noOfOccurences = (occurencesOfWords[sortedarray[i]]==undefined?
1 : ++occurencesOfWords[sortedarray[i]]);
occurencesOfWords[sortedarray[i]] = noOfOccurences;
}
console.log(JSON.stringify(occurencesOfWords));
So you'll get something like this in the end:
{"Multimedia":3,"XYZ":2}
.search is undefined and isn't a function on the array.
But exists on the current string you want to check ! Just select the current string in the array with sortedarray[i].
Fix your code like that:
for(var i = 0; i < sortedarray.length; i++)
{
if(sortedarray[i].search("Multimedia") === true)
{
multimedia += 1;
}
}
console.log(multimedia);
var record = "HENRY|5|58|L581"
How do I change the above to:
record now equals "HENRY|Five|58|L581"
I know how to retrieve the index of the first '|' and the second '|' .. I know how to retrieve the number '5' into a string.
But I have no idea how to actually replace that 5 with the word Five.
The part |5| could be any number from 1-50
Something like that ?
record = record.replace('|5|', '|FIVE|');
Following edit :
To replace any number by FIVE, you can do
record = record.replace(/\|\d+\|/, '|FIVE|');
If you want to replace with something depending of the number (maybe you want TEN when the number is 10), then you'll have to do some work :
record = record.replace(/\|\d+\|/, function(str) {
var number = parseInt(str,10);
return 'FIVE'; // here build a new string and return it
});
You can do this, for example:
var record = "HENRY|5|58|L581"
var recordArray = record.split("|");
for (var i = 0; i < recordArray.length; i++) {
if (recordArray[i] === "5") {
recordArray[i] = "FIVE";
}
}
record = recordArray.join("|"); // or record = recordArray.toString();
Is this what you want to achieve?
UPDATE
If you want any number, you can set it into a function:
function changeNumber(textVar, valueToChange, replaceText) {
var recordArray = textVar.split("|");
for (var i = 0; i < recordArray.length; i++) {
if (recordArray[i] === valueToChange) {
recordArray[i] = replaceText;
}
}
return recordArray.join("|"); // or recordArray.toString();
}
See demo.
I presume you don't want to replace any number with "five", you want to replace with the actual string representing number.
var repl = [0, 1, ....];
var to = ["zero", "one", ...];
var recordArray = record.split("|");
for (var i = 0; i < recordArray.length; i++) {
recordArray[i] = to[indexOf(recordArray[i], repl)];
}
finStr = recordArray.join("|");