Format currency type with Javascript - javascript

In c# you can do this
String.format(5000, "$###,###,##0.00;-$###,###,##0.00;$0.00")
Which will output: $5,000
Or you can do this
String.format(-5000, "$###,###,##0.00;-$###,###,##0.00;$0.00")
Which will output: -$5,000
How do I do the same in Javascript??
UPDATE: I would also need to format a currency like this
String.format(-5000, "###.###.##0.00€;-###,###,##0.00€;0.00€")
Which would output: 5.000,00 €

you should really consider using toLocaleString so your code can rely on configuration settings like locale and currency rather than customized string format patterns.
const formatCurrency = (num, locale = 'en-US', currency = 'USD', minimumFractionDigits = 2) => {
if (isNaN(num)) {
return num;
}
return num.toLocaleString(locale, {style: 'currency', currency, minimumFractionDigits});
};
Here is an example fiddle

I Ended up rolling my own:
app.filter('formatMoney', ['$filter', function ($filter) {
return function (value, format) {
var v = format.split(';');
var index = 2;
if (value > 0)
index = 0;
else if (value < 0)
index = 1;
else {
return v[index];
}
var len = v[index].length;
var fIndex = v[index].indexOf('#');
var lIndex = v[index].lastIndexOf('0');
var f = v[index].substring(fIndex, lIndex + 1);
var symbolFirst = '';
var symbolLast = '';
if (lIndex !== len - 1) {
symbolLast = v[index].substring(len, len - 1);
}
if (fIndex > 0) {
symbolFirst = v[index].substring(0, fIndex);
}
var valueStr = value.toFixed(2).toString();
for (var i = f.length - 1; i > 0 && valueStr.length > 0; i--) {
var slice = valueStr.slice(-1);
if (f[i] === '#' || f[i].isNumeric()) {
valueStr = valueStr.slice(0, -1);
if (slice.isNumeric()) {
f = f.replaceAt(i, slice);
var j = valueStr.length - 1;
while (j > 0 && !valueStr[j].isNumeric()) {
valueStr = valueStr.slice(0, -1);
j = j - 1;
}
}
}
}
return symbolFirst + f.substr(f.search(/\d/), f.length - 1) + symbolLast;
};
}]);

Related

Converting unary string of units to binary string only works once (Javascript)

I built an integer conversation from unary string of units = '1' to a binary representation in string format!
The function only works once and is limited to the number 31
here is my approach in javascript - can you help or explain?
func_unary_to_digit = function(p_reg1) {
var grouper = {
group:''
};
var unit = '1';
var p_sys = 2;
var i_grp = 0;
var t1_reg = p_reg1;
var lw1_unary = '';
var rw1_unary = '';
var lw2_unary = '0';
var rw2_unary = '';
for(it_g = 0; it_g < p_sys; it_g++) {
grouper.group += unit;
}
if(p_reg1.length === 1) {
lw1_unary = '';
rw1_unary = unit;
} else {
for (it_s = 0; it_s <= t1_reg.length; it_s++) {
lw1_unary = '';
i_grp = 0;
for (it_c = 0; it_c < t1_reg.length; it_c++) {
if (it_c % grouper.group.length === 1) {
lw1_unary += unit;
i_grp++;
}
}
if (t1_reg.length % grouper.group.length === 0) {
//rw1_unary += inf;
rw1_unary += '0';
}
if (t1_reg.length % grouper.group.length === 1) {
rw1_unary += unit;
}
if (lw1_unary.length === 1) {
lw1_unary = '';
rw1_unary += unit;
}
t1_reg = lw1_unary;
}
}
rw1_unary = rw1_unary.split('').reverse().join('');
console.log(rw1_unary);
}

When i pass 1 into n i do not get [0,1] i get [1]?

This is Fibonacci Generator function that i have created but for some reason i can't seem to get the output for 1 = [0,1] . While it works alright for other conditions.If somebody can point me at what i am doing wrong here.
function bl(n) {
var output = [];
var firstNo = 0;
var secondNo = 1;
if (n === 0) {
output.push(0);
}
if (n === 1) {
output.push(0);
output.push(1);
} else {
for (var i = 0; i < n; i++) {
var sum = firstNo + secondNo;
firstNo = secondNo;
secondNo = sum;
output.push(sum);
}
return output;
}
}
console.log(bl(1));
return output had to be executed for all conditions so just execute it at end of your function.
function bl(n) {
var output = [];
var firstNo = 0;
var secondNo = 1;
if (n === 0) {
output.push(0);
}
if (n === 1) {
output.push(0);
output.push(1);
} else {
for (var i = 0; i < n; i++) {
var sum = firstNo + secondNo;
firstNo = secondNo;
secondNo = sum;
output.push(sum);
}
}
return output;
}
console.log(bl(1));

javascript longest palindrome while loop

how to return '' when called one letter?
function isPalindrome(s) {
var rev = s.split("").reverse().join("");
return s == rev;
}
function longestP(string) {
var maxP = ''; var maxL = 0;
var i = 0;
while(i < string.length) {
length = 1;
while(i+length <= string.length) {
substring = string.slice(i,length);
if(isPalindrome(substring)) {
if(substring.length > maxL) {
maxL = substring.length;
maxP = substring
}
}
length = length +1
}
i++
}
return maxP
}
console.log(longestP('abba'))
console.log(longestP('a'))

Check password strength against an API value

I get my password spec from an API which then I split the object into the needed fields and check that I have the required number of lower, upper, special and length of my password.
function isStrong(passwordChecker) {
if (!passwordChecker) {
return false;
}
debugger;
var securityOption = JSON.parse(localStorage.getItem("Security"));
var MinLength = securityOption.PasswordMinRequiredLength;
var SpecialChars = securityOption.PasswordMinRequiredNonalphanumericCharacters;
var MinLowercase = securityOption.PasswordMinRequiredLowercase;
var MinUppercase = securityOption.PasswordMinRequiredUppercase;
//LenghtCheck
if (passwordChecker.length < MinLength);
return false;
if (!CountSpecialChars(passwordChecker) > SpecialChars) {
return false;
}
if (MinLowercase > 0) {
if (!CountLowerCase(passwordChecker) > MinLowercase) {
return false;
}
}
if (MinUppercase > 0) {
if (!CountUpperCase(passwordChecker) > MinLowercase) {
return false;
}
}
}
function CountSpecialChars(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
Count++;
}
}
}
function MinLowercase(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 97 && text[i] <= 122) {
Count++;
}
}
}
function MinUppercase(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 65 && text[i] <= 90) {
Count++;
}
}
}
Now what I want to do is, check the different conditions as a whole and if all of the conditions are true then change the class to green..
$(pageId + ' #password').bind('keyup', function () {
var currentpassword = $(pageId + ' #password').val();
if (isStrong(currentpassword)) {
$(pageId + ' #password').addClass('green');
} else {
$(pageId + ' #password').addClass('red');
}
});
I am not sure how to check the conditions as a whole and return an overall true because as I start trying in my password it instantly changes to green as in my password spec you do not need any UpperCase or LowerCase letters so on any input of a char it returns true..
You should refactor your functions so that they accept both the string and the parameter and return true or false. For example:
function CountSpecialChars(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
Count++;
}
}
}
if (!CountSpecialChars(passwordChecker) > SpecialChars) {
return false;
}
Should instead be:
function CountSpecialChars(text, min) {
var count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
count++;
}
}
return count > min;
}
return CountSpecialChars(passwordChecker, SpecialChars);
Also, as a bonus, you could also avoid that for loop for those functions by using replace, like so:
function MinChars(text, min) {
return text.length > min;
}
function MinUppercase(text, min) {
var non_uppers = /[^A-Z]/g;
var uppers = text.replace(non_uppers, text);
return uppers.length > min;
}
function MinLowercase(text, min) {
var non_lowers = /[^a-z]/g;
var lowers = text.replace(non_lowers, text);
return lowers.length > min;
}
function MinSpecialChars(text, min) {
var non_specials = /[^!-\?]/g;
var specials = text.replace(non_specials, text);
return specials.length > min;
}
Now with those functions, you can have:
if !MinChars(pw, MinLength) return false;
if !MinSpecialChars(pw, SpecialChars) return false;
if !MinLowercase(pw, MinLowercase) return false;
if !MinUppercase(pw, MinUppercase) return false;
return true;

Why my function return an array with only one element?

I am writing a function that will return an array with prime numbers.
The function should return an array with n elements. (n is a parameter) But it returns only one element. Why?
My codes:
function findPrimes(n)
{
var arr = [];
var currIndex = 0;
var sqrtNum;
var ceiledNum;
var ceiledIndex = 0;
var currCompose;
var res;
for (initNum = 2; arr.length < n; ++initNum)
{
sqrtNum = Math.sqrt(initNum);
ceiledNum = Math.ceil(sqrtNum);
for (currCompose = 2; currCompose <= ceiledNum; ++currCompose)
{
res = initNum % currCompose;
if (res == 0 && initNum != currCompose)
{
break;
}
else if (res == 0 && initNum == currCompose)
{
arr[currIndex] = initNum;
++currIndex;
break;
}
else if (res != 0 && initNum != currCompose)
{
continue;
}
else
{
console.log("Impossible result!");
}
}
}
return arr;
}
findPrimes(2); //return 2
findPrimes(10); //return 2 too
Jsbin
You should not be comparing initNum to currCompose. Keep in mind that initNum is the number you are checking (say, 71), and currCompose will be at most ceil(sqrt(initNum)) (say 9), so the two will never be equal.
Also note that it is best to append to the list and verify that no divisors where found only after the inner loop has finished.
This modified version works.
function findPrimes(n)
{
var arr = [];
var currIndex = 0;
var sqrtNum;
var ceiledNum;
var ceiledIndex = 0;
var currCompose;
var res;
var initNum;
for (initNum = 2; arr.length < n; ++initNum)
{
sqrtNum = Math.sqrt(initNum);
ceiledNum = Math.ceil(sqrtNum);
for (currCompose = 2; currCompose <= ceiledNum; ++currCompose)
{
res = initNum % currCompose;
if (res == 0 && initNum != currCompose)
{
break;
}
}
if (currCompose == ceiledNum+1)
{
arr[currIndex] = initNum;
++currIndex;
}
}
return arr;
}
var primes = findPrimes(6);
document.write(primes);
correct Line 14 of your code as follows and it works like charm.
for (currCompose = 2; currCompose <= initNum; ++currCompose)
function FindPrime(numbers){
if(numbers.constructor === Array){
output = [];
for (var i = numbers.length - 1; i >= 0; i--) {
if(isPrime(numbers[i]) == true){
output.push(numbers[i]);
};
};
return output;
}
}
function isPrime(numb){
if (numb % 2 == 0) return false;
for (var i=3; i<= Math.sqrt(numb); i = i + 2) {
if (numb % i == 0) {
return false;
}
}
return true;
}
numbers = [1,2,3,4,5];
test = FindPrime(numbers);
console.log('testing', test);

Categories