Formatting numbers in Angular.js - angularjs

I have a variable in Angular.js that I should fill like that :
values.push({x: '' + d.x + 'h', y: d.y / 100})
d.x and d.y are numbers that I should display in a ndv3 multiBarChart.But I should format the numbers as if I have 2500, I obtain 2 500.How can I do it ?

I write Angularjs filters Example.jsfiddle
HTML File
<div>
<label >{{"4876931.19" | numberFilter}}</label>
</div>
App Js
angular.module('myApp', ['filters']);
Filter js
angular.module('filters', []).filter('numberFilter', [function () {
return function (number) {
if (!angular.isUndefined(number)) {
var parts = number.split(".");
var str = parts[0].toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1 ");
if(parts[1] !== undefined){
str+="."+parts[1];
}
return str;
}
};
}]);
Updated Code

Here is a small Javascript function which parses the provided number and format it to the desired output:
function formatNumber(str) {
var parts = (str + "").split("."),
main = parts[0],
len = main.length,
output = "",
i = len - 1;
while(i >= 0) {
output = main.charAt(i) + output;
if ((len - i) % 3 === 0 && i > 0) {
output = " " + output;
}
--i;
}
// put decimal part back
if (parts.length > 1) {
output += "." + parts[1];
}
return output;
}
Calling this function with the provided number:
formatNumber(4876931.19) // output will be: 4 876 931.19
function formatNumber(str) {
var parts = (str + "").split("."),
main = parts[0],
len = main.length,
output = "",
i = len - 1;
while(i >= 0) {
output = main.charAt(i) + output;
if ((len - i) % 3 === 0 && i > 0) {
output = " " + output;
}
--i;
}
// put decimal part back
if (parts.length > 1) {
output += "." + parts[1];
}
return output;
}
console.log(formatNumber(4876931.19))

Related

Run loop array in order

I am trying to run satellite image animation with buttons controls .l have array of dates satellite image animation.
["20200922", "20200923", "20200924", "20200925", "20200926", "20200927", "20200928"]
My code below is working fine . But when i run the code i have random output array , is not running as orderly
Code :
saturation: number = 1000
timeStops: any[];
imgs:any[]
_index :number = 0;
index: number = 0;
date$: Observable<any>;
image$: Observable<any>;
datepush: any[][];
datearray:any[]
play() {
const now = moment()
this.timeStops = [];
this.datearray = [];
for (let i = 0; i < 11; i++) {
now.subtract(15, 'minutes')
this.timeStops.push(this.roundTimeQuarterHour(now).utc().format('YYYYMMDD'));
this.imgs= [
new Image().src = "" + this.timeStops[10] + "T000000/time/00/image",
new Image().src = "" + this.timeStops[9] + "T000000/time/24/image",
new Image().src = "" + this.timeStops[8] + "T000000/time/48/image",
new Image().src = "" + this.timeStops[7] + "T000000/time/72/image",
new Image().src = "" + this.timeStops[6] + "T000000/time/96/image",
new Image().src = "" + this.timeStops[5] + "T000000/time/120/image",
new Image().src = "" + this.timeStops[4] + "T000000/time/144/image",
new Image().src = "" + this.timeStops[3] + "T000000/time/168/image",
new Image().src = "" + this.timeStops[2] + "T000000/time/192/image",
new Image().src = "" + this.timeStops[1] + "T000000/time/216/image",
new Image().src = "" + this.timeStops[0] + "T000000/time/240/image",
];
}
this.imgs.sort()
this.datearray.sort()
console.log(this.imgs)
var fortnightStart = moment();
for (let i = 1; i <= 7; i++) {
// 1, not i
this.datearray.push(fortnightStart.add(1, "days").format("YYYYMMDD"));
}
console.log(this.datearray);
console.log(this.index)
if (Math.abs(this._index) < this.imgs.length &&Math.abs(this._index) < this.datearray.length) {
this._index = this.imgs.length;
this._index = this.datearray.length;
}
this.image$ = interval(this.saturation).pipe(
map(() => {
return this.imgs[this.calculateIndex()];
}),
startWith(this.imgs[10])
);
this.date$ = interval(this.saturation).pipe(
map(() => {
return this.datearray[this.calculateIndex()];
}),
startWith(this.datearray[0])
);
}
calculateIndex(): number {
if (Math.abs(this._index) >= this.imgs.length * 3 &&Math.abs(this._index) >= this.datearray.length * 3) {
this._index = this._index % this.imgs.length;
this._index = this._index % this.datearray.length;
}
if (this.stoploop) {
this.index = this._index % this.imgs.length
this.index = this._index % this.datearray.length
return this.index;
} else {
if (this.isBackward) {
this.index = Math.abs(--this._index % this.imgs.length);
this.index = Math.abs(--this._index % this.datearray.length);
return this.index;
} else {
this.index = (++this._index % this.imgs.length);
this.index = (++this._index % this.datearray.length);
return this.index;
}
}
}
the output :
There is any way i can make the output loop as orderly ?
Live code
Your script randomizing the index, checkout I've modified your code.
startAnimation(){
this.timeOutSubsription = setInterval(()=>{
console.log(this.index)
if(this.isBackward){
this.index--;
if(this.index<0){
this.index = this._index;
}
} else{
this.index++;
if(this.index>this._index){
this.index = 0;
}
}
this.image$.next(this.imgs[this.index])
this.date$.next(this.datearray[this.index])
}, this.saturation);
}
Hope this solves your issue.

How to convert Alphanumeric Values to value ranges in Typescript?

myArray = ["AB01","AB02","AB03","AB04","AB11","BC12","BC13", "SB33"];
// expected string "AB01-AB04, AB11, BC12-BC13, SB33"
The letters can be one or two characters. Digits can be two or three characters.
Ex: A001, A002, AB001, AB002, AC01, AC02, B01, B02.
Only these formats are possible.
How to achieve this in a simplified manner?
let myArray = ["AB01","AB05","ABCDEFG01123","ABCDEFG01124","AB02","AB03","AB04","AB11","BC12","BC13", "SB33"];
function getRanges(array, group) {
var ranges = [], rstart, rend;
for (var i = 0; i < array.length; i++) {
rstart = array[i];
rend = rstart;
while (array[i + 1] - array[i] == 1) {
rend = array[i + 1];
i++;
}
ranges.push(rstart == rend ? group+rstart+'' : group+rstart + '-' + group+rend);
}
return ranges;
}
// group first.
let groups = myArray.reduce((groups,item)=>{
let belongsTo = item.match(/[a-zA-Z]/g).join('');
groups[belongsTo] ? groups[belongsTo].push(item) :groups[belongsTo]=[item];
return groups;
},{})
let expectedString = Object.entries(groups).reduce((output,[key,value])=>{
output=`${output}${output.length ? ', ' : ''}${getRanges(value.map(i=>i.match(/[0-9]/g).join('')),key)}`;
return output;
},'');
console.log(expectedString);
// expected string "AB01-AB04, AB11, BC12-BC13, SB33"

Creating a javascript array to localstorage not returning desired result

I'm trying to create an array to localstorage containing some gear box values, witch I then need again to do some more calculations with specific array[?].value.
The problem I'm encountering is that the created entry returns only 2 array entries, although all entries are there but the " is at the beginning and then at the second last entry and then before and after the last entry.
These are the values generated.
spd_Dev = ["202.391,172.876,120.451,102.601,85.173,72.664,61.701,52.706,45.116,38.510,32.326,27.407,22.910,19.536,16.585,14.195,12.228","10.401"]
When I used to use a fixed array I've entered it as:
var spd_Dev = [202.391, 172.876, 120.451, 102.601, 85.173, 72.664, 61.701, 52.706, 45.116, 38.510, 32.326, 27.407, 22.910, 19.536, 16.585, 14.195, 12.228, 10.401];
So my question is how to write this values to localstorage and read again from localstorage so that I can use this values as an array.
This is what I'm trying to work.
var D_RatioId = data.truck.make + data.truck.model + "D_Ratio"
var G_RatioId = data.truck.make + data.truck.model + "G_Ratio"
var fGr = data.truck.forwardGears;
var gr = data.truck.displayedGear;
var Rpm = data.truck.engineRpm * 100;
var spd = data.truck.speed;
var T_Dia = 1008.3;
if (localStorage.getItem(G_RatioID) == undefined) {
localStorage.setItem(G_RatioID, '');
var fG_Rat = [localStorage.getItem(G_RatioID)];
} else {
var fG_Rat = [localStorage.getItem(G_RatioID)];
}
var spd_Dev = localStorage.getItem(Spd_DevId);
spd_Dev = spd_Dev ? spd_Dev.split(', ') : [];
if (localStorage.getItem("i") == undefined) {
localStorage.setItem("i", 1);
var i = localStorage.getItem("i");
} else {
var i = localStorage.getItem("i");
}
if (i <= fGr && spd > 0.5) {
if (i <= fGr + 1) {
if (i == gr) {
if (RPM > 1450) {
var G_Ratio = Math.abs(Rpm / D_Ratio * (Math.PI * T_Dia / 1000) * 60 / spd / 1000, 2).toFixed(2);
var spd_D = Math.abs(RPM / (RPM / G_Ratio / D_Ratio * (Math.PI * T_Dia / 1000) * 60 / 1000) * 0.821932).toFixed(3);
fG_Rat.push(G_Ratio);
spd_Dev.push(spd_D);
i++;
localStorage.setItem("i", i);
var G_RatioValue = fG_Rat;
var Spd_DevValue = spd_Dev;
SetG_Ratio(G_RatioID, G_RatioValue);
SetSpd_Dev(Spd_DevId, Spd_DevValue);
localStorage.setItem("spd_Dev", JSON.stringify(Spd_DevValue));
}
}
}
}
function SetG_Ratio(G_RatioID, G_RatioValue) {
localStorage.setItem(G_RatioID, G_RatioValue);
console.log(G_RatioID, G_RatioValue);
}
function SetSpd_Dev(Spd_DevId, Spd_DevValue) {
localStorage.setItem(Spd_DevId, Spd_DevValue.toString());
console.log(Spd_DevId, Spd_DevValue, Spd_DevValue.length);
}
if (spd >= 0) {
var spd_Dev = [localStorage.getItem(Spd_DevId)];
var spD_D = JSON.parse(spd_Dev);
for (i = 1; i < (fGr + 1); i++) { // Some more code dependant on the above results //
why don't you use LSM.js? it will make everything simpler. you can put the array as an array so that it will return the full array only, you will not need to use split(),
https://github.com/kevinj045/LSM_js
var lsm = new LSM("G_RatioID");
var G_RatioValue ["202.391,172.876,120.451,102.601,85.173,72.664,61.701,52.706,45.116,38.510,32.326,27.407,22.910,19.536,16.585,14.195,12.228","10.401"];
lsm.set("G_RatioID",G_RatioValue);
console.log(lsm.get("G_RatioID")); // it will return the full array

Problems with includes() function and array comparsion

As a part of whole procedure, I want to compare user's input (as array) with union of two randomly given arrays. I can not use array.sort() and comparison of arrays element by element, because it's enough to have just one different element in input array and after sorting more than just one element will be identified as "wrong one" (example: array "union" after sorting = [11,13,17,18], array "upis" (user's input) after sorting = [7,11,13,18] so if I compare element by element, which I've tried in original code, all first three elements are identified as wrong...)
That's why I've switched to array.includes() and I've spend last 5.5 hours trying to find where am I wrong and just can't find it so I'm going slightly mad... In few hours I'm supposed to be at work but I'm losing my mind because of this...
THE PROBLEM IS WITHIN checkInput() FUNCTION... The code just won't and won't recognize input elements (array "upis") within "union" array... Can't figure out why???
Any help more then appreciated!
<script>
//----------- 1.) Kreiraj dva nasumična niza i uniju -----------
var arrA = []; //od 3 do max 6 članova
var arrB = []; //od 2 do max 5 članova
while (arrA.length < Math.floor(Math.random() * 4) + 3) {
var randomnumber = Math.floor(Math.random() * 20) + 1;
if (arrA.indexOf(randomnumber) > -1) continue;
arrA[arrA.length] = randomnumber;
}
while (arrB.length < Math.floor(Math.random() * 4) + 2) {
var randomnumber = Math.floor(Math.random() * 20) + 1;
if (arrB.indexOf(randomnumber) > -1) continue;
arrB[arrB.length] = randomnumber;
}
var union = [...new Set([...arrA, ...arrB])];
document.write("A = " + arrA + "<br>");
document.write("B = " + arrB + "<br>");
//----------- 2.) Funkcija za dodavanje text box-ova -----------
function addFields() {
// Broj text box-ova koje treba kreirati
var number = union.length;
// <div> u koji će se dinamično dodati text box-ovi
var container = document.getElementById("container");
// Obriši prethodni zapis u <div>
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
// Tekst A U B
//container.appendChild(document.createElement("br"));
container.appendChild(document.createTextNode("A ∪ B = "));
for (i = 0; i < number; i++) {
// Kreiraj <input> element i definiraj stil
var input = document.createElement("input");
input.type = "text";
input.id = "element" + i;
input.style.width = 25;
container.appendChild(input);
// Dodaj zarez poslije svakog input box-a, osim posljednjeg
if (i < number - 1) {
container.appendChild(document.createTextNode(", "));
}
}
// Pokaži gumb Provjeri
document.getElementById("provj").style.visibility = "visible";
}
//----------- 3.) Provjera upisa -----------
function checkInput() {
var upis = [];
var greske = [];
// Pohrani upis u niz
for (i = 0; i < union.length; i++) {
var privr = document.getElementById("element" + i).value;
upis.push(privr);
}
for (i = 0; i < upis.length; i++) {
// ako je neko polje nepopunjeno, obavijesti i prekini petlju
if (upis[i] === "") {
alert("Treba upisati sve članove unije skupova!");
greske = [];
//npr. prva dva upisa kriva, ostala polja nepopunjena - iako ima
//praznih polja, prekida se procedura ali se kod prva dva upisa
//popunio niz greške i onda će ih pokazati
break;
}
// u protivnom
else {
var n = union.includes(upis[i]);
alert(upis[i] + " " + n);
if (n === false) {
greske.push(upis[i]);
} else {
//ništa
}
}
}
if (greske.length > 0) {
alert("Krivo upisani članovi: " + greske);
}
}
</script>
<div id="container">
<button onclick="addFields()">Upiši članove unije</button>
</div>
<button id="provj" style="visibility:hidden" onclick="checkInput()">Provjeri</button>
You are comparing numbers with strings. Just add + to the includes parameter:
var n = union.includes(+upis[i]);
This will force the string to be unboxed as a number and your includes will work as expected.
You other option is to convert those strings to numbers and then no unboxing will be needed.

When to set caret position in $parser method of angularJS

I'm using ngModelController for formatting using input element. But I'm unable to set the caret position, if the user tries to enter any digit in the beginning or in the middle. As the caret alway jumps at the end.
What is the best place for calling set cursor?
ngModelController.$parsers.unshift(function (viewValue) {
var plainNumber = viewValue.replace(/ /g, '');
// $log.info(`viewValue = ${viewValue}`);
console.log(`$modelValue = ${ngModelController.$modelValue} | $viewValue = ${ngModelController.$viewValue}`);
console.log(`cursorPos = ${cursor.getCursorPos(elem[0])}`);
var newVal = ""
for (var i = 0; i < plainNumber.length; i++) {
if (i === 3 || i === 6) {
newVal += " ";
}
newVal += plainNumber[i];
}
cursor.setCursorPos(cursor.getCursorPos(elem[0]) + 1, elem[0]);
// $log.info(`newVal = ${newVal}`);
elem.val(newVal);
return plainNumber;
});
similar question:
Preserving cursor position with angularjs
But I've added the below code, may be useful to other.
ngModelController.$parsers.unshift(function (viewValue) {
var plainNumber = viewValue.replace(/ /g, '');
// $log.info(`viewValue = ${viewValue}`);
console.log(`$modelValue = ${ngModelController.$modelValue} | $viewValue = ${ngModelController.$viewValue} | viewValue = ${viewValue} | cursorPos = ${cursor.getCursorPos(elem[0])} | oldVal = ${oldVal}`);
var newVal = ""
for (var i = 0; i < plainNumber.length; i++) {
if (i === 3 || i === 6) {
newVal += " ";
}
newVal += plainNumber[i];
}
if(newVal === viewValue) {
return viewValue;
}
// $log.info(`newVal = ${newVal}`);
var lastCursorPos = cursor.getCursorPos(elem[0]);
elem.val(newVal);
ngModelController.$setViewValue(newVal);
ngModelController.$render();
//cursor.setCursorPos(cursor.getCursorPos(elem[0]) + 1, elem[0]);
elem[0].setSelectionRange(lastCursorPos + 1, lastCursorPos + 1);
oldVal = newVal;
return plainNumber;
});

Resources