In javascript, I have some numbers.
23, 100000, 5000, 45.543
I want to convert each number into a well-formatted string
e.g.
'23.00', '1,000,000.00', '5,000.00' , '45.54'
How do I do that in javascript ?
I can do it easily in java (where there is a textformatter class for this)
thanks,
function CommaFormatted(amount)
{
var delimiter = ","; // replace comma if desired
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
Related
I am trying to randomize each characters casing in a string. My code so far goes as following:
var message = 'This message is for testing'
for (var i = 0; i < message.length; i++) {
var random_number = Math.round(Math.random() * 10 + 1);
if(random_number % 2 == 0) {
message.charAt(i).toUpperCase();
}
}
console.log(message)
Problem is that even when giving out the letters and numbers via console.log it shows that the numbers would result in an uppercase, but the letters stay low
You just need to store your changes, in for example a different string.
var message = 'This message is for testing';
var newMessage = '';
for (var i = 0; i < message.length; i++) {
var random_number = Math.round(Math.random() * 10 + 1);
if(random_number % 2 == 0) {
newMessage += message.charAt(i).toUpperCase();
}else{
newMessage += message.charAt(i);
}
}
console.log(newMessage);
Build a new string with adding char for char in randomly upper-/lowercase to it.
var message = 'This message is for testing'
let result ="";
for (var i = 0; i < message.length; i++) {
var random_number = Math.round(Math.random() * 10 + 1);
if(random_number % 2 == 0) {
result += message.charAt(i).toUpperCase();
} else {
result += message.charAt(i);
}
}
console.log(result)
Ciao, concat char to a string like this example:
var message = 'This message is for testing'
let stringresult = "";
for (var i = 0; i < message.length; i++) {
var random_number = Math.round(Math.random() * 10 + 1);
if(random_number % 2 == 0) {
stringresult += message.charAt(i).toUpperCase();
}
else stringresult += message.charAt(i);
}
console.log(stringresult)
More info:
Input/Output Details:
[time limit] 4000ms (js)
[input] integer n
A positive two-digit integer.
Constraints:
10 ≤ n ≤ 99.
[output] integer
The sum of the first and second digits of the input number.
Below is my attempt
function addTwoDigits(n) {
var num = n;
var n = num.toString();
var sum = n[0] + n[1];
return sum;
}
var userInput= prompt('enter a number');
if (userInput>= 10 && userInput<=99) {
return addTwoDigits(userInput);
}
console.log(addTwoDigits(n));
function addTwoDigits (input){
var numString = input.toString()
var numArray = numString.split('')
var digitOne = []
var digitTwo = []
for (var i = 0; i < numArray.length; i++){
digitOne.push(numArray[0])
digitTwo.push(numArray[1])
}
for (var i = 0; i < digitOne.length; i++){
digitOne.pop()
}
for (var i = 0; i < digitTwo.length; i++){
digitTwo.pop()
}
var numOne = parseInt(digitOne)
var numTwo = parseInt(digitTwo)
var sum = numOne + numTwo
return sum;
}
n[0] and n[1] are strings. + is only addition for two numbers, but concatenation for any other case, so "2" + "9" is back at "29" rather than 11 that you hope for. Use parseInt(n[0]) (and similar for n[1]) to turn them into something you can do arithmetic with.
Alternately, you can do this purely numerically, without ever touching strings:
var tens = Math.floor(n / 10);
var ones = n % 10;
var sum = tens + ones;
Here is my answer in Java.
int addTwoDigits(int n) {
String number = String.valueOf(n);
int[] nums = new int [number.length()];
for(int i = 0; i < number.length(); i++){
nums[i] = Character.getNumericValue(number.charAt(i));
}
return nums[0] + nums[1];
}
function solution(n) {
let number = n.toString();
console.log("Here is my number", );
let convertedNum = number.split('');
console.log("Here is my converted number: ", convertedNum.length)
let sum = 0;
for(let i = 0; i < convertedNum.length; i++){
sum += parseInt(convertedNum[i])
}
return sum;
}
Use parseInt
function addTwoDigits(n) {
var num = n;
var n = num.split("");
var sum = parseInt(n[0]) + parseInt(n[1]);
return sum;
}
var userInput = prompt('enter a number');
if (userInput >= 10 && userInput <= 99) {
console.log(addTwoDigits(userInput));
}
function addTwoDigits(n) {
let str = n.toString()
if (n >= 10 && n < 100){
return +str[0] + +str[1]
}
}
function solution(n) {
let a = Math.floor(n/10);
let b = n%10;
return a + b;
}
I used the charAt method and parseInt function to get an answer. You can see it in this code snippet:
function addTwoDigits(n) {
var string = n.toString();
var sum = parseInt(string.charAt(0)) + parseInt(string.charAt(1));
return sum;
}
var userInput = prompt('enter a number');
if (userInput >= 10 && userInput <= 99) {
console.log(addTwoDigits(userInput));
}
function addDigits(source) {
return source
/* convert number to string and split characters to array */
.toString().split('')
/* convert char[] to number[] */
.map(function (elm) { return Number(elm); })
/*
accumilate all numbers in array to value, which is initally zero.
REF: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Examples
*/
.reduce(function (result, current) { return result + current; }, 0)
}
function validate(source) {
if (typeof(source) == "undefined" || source == null) { throw 'value can not ne NULL ...'; }
if ((typeof(source) !== 'number')) { throw 'value has to of NUMBER type ....'; }
if ((source % 1)) { throw 'value has to be an INTEGER ....'; }
if (!(source >= 10 && source <= 99)) { throw 'value is out of range 10-99 ....'; }
}
/* TESTING ......*/
var samples = [null, 'sdsad', 9.9, 9, 10, 99, 100];
samples.forEach(function (elm) {
try {
validate(elm);
console.log(elm + ': ' + addDigits(elm));
} catch (exp) {
console.log(elm + ': ' + exp);
}
});
<
$(document).ready(function(){
var $number = $('input[name=number]'),
$result = $('.result');
$('input[name="calculate"]').on('click',function(){
var total = parseInt($number.val()),
decens = Math.floor(total/10),
units = total % 10;
if (total >9 && total < 100){
$result.html(decens + units);
}
else {
$result.html("Total must be an integer between 10 and 99");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="number" />
<input type="submit" name="calculate" value="Calculate"/>
Result:<span class="result"></span>
Here is a example from me
function solution(n) {
let num = n;
let num2 = n.toString().split("");
let sum = parseInt(num2[0]) + parseInt(num2[1]);
return sum;
}
Follow,
function solution(n) {
let num = n.toString().split('')
return parseInt(num.reduce((acc, cur) => Number(acc) + Number(cur), 0))
}
function solution(n) {
let num = n.toString().split('')
return parseInt(num.reduce((acc, cur) => Number(acc) + Number(cur), 0))
}
document.getElementById("input29").innerHTML = solution(29);
document.getElementById("input48").innerHTML = solution(48);
<!DOCTYPE html>
<html>
<body>
<h2>Example</h2>
Input 29: <p id="input29"></p>
<br>
Input 48: <p id="input48"></p>
</body>
</html>
i have one phone number text-field.Now,i want to apply regex through java-script. for that i used below code.but it is not accept 10 digit.would any told me that what is wrong with below code.
java script code:-
function val(value) {
var p = phonevalue1
p = p.replace(/[^\d]*/gi, "")
if (p.length <= 5) {
value.value = p;
}
else if (p.length > 5 && p.length < 9) {
var a = p.substring(0, 5);
var b = p.substring(5, p.length);
var c = a + "-" + b;
value.value = c;
}
else if (p.length >= 9) {
var len = p.length;
var a = p.substring(0, 5);
var b = p.substring(5, len);
var c = a + "-" + b;
value.value = c.substring(0, 10);
}
}
From what I can tell you want the following
5 or less digits just add digits to value property of value object
6 - 8 digits add hyphen after fifth digit as in 12345-678
9 digits or greater 12345-6789
NOTES:
value.value means value is an {};
phonevalue1 is undefined in the function, so I will assume it is defined in the parent scope and is some string of numbers.
The code you have provided can be simplified a bit. I will make some adjustments and you'll have to adjust how your code block handles the function. K?
function val(value) {
var p = phonevalue1
p = p.replace(/[^\d]*/gi, "")
if (p.length <= 5) {
value.value = p;
}
else if (p.length > 5 && p.length < 9) {
var a = p.substring(0, 5);
var b = p.substring(5, p.length);
var c = a + "-" + b;
value.value = c;
}
else if (p.length >= 9) {
var len = p.length;
var a = p.substring(0, 5);
var b = p.substring(5, len);
var c = a + "-" + b;
value.value = c.substring(0, 10);
}
}
Change to this...
NOTE: Where value is your object as you stated,
var value = {};
var phonevalue1 = "12345";
var phonevalue2 = "12345678";
var phonevalue3 = "1234567890";
value.value = phonevalue1.replace(/(^\d{5})/, "$1-").replace(/-$/, '');
=> { value: "12345" };
value.value = phonevalue2.replace(/(^\d{5})/, "$1-").replace(/-$/, '');
=> { value: "12345-678" };
value.value = phonevalue3.replace(/(^\d{5})/, "$1-").replace(/-$/, '');
=> { value: "12345-67890" };
If you want to use a function as you have, I will try to make the same thing work, but the way your code is structured is not recommended as it is unnecessarily long and confusing.
function addHyphen( numString ){
return numString.replace(/(^\d{5})/, "$1-").replace(/-$/, '');
}
value.value = addHyphen( phonevalue1 );
Hope this helps...
Seeing all the people talking about longest substring in alphabetical order in Python, I have decided to try it in JS.
The function should look for the longest substring inside a given string, where letters are ordered alphabetically.
Here is what I have:
var s = 'azcbobobegghakl'
function substringChecker(s) {
var longestSub = "";
for (var i = 0; i < s.length; i++) {
var count = 0;
var currSub = "";
while((i+count)<=s.length){
var curr = i+count;
var next = curr+1;
var prev = curr-1;
if(curr !== s.length-1) {
if(s[curr] <= s[next]){
currSub += s[curr]
} else {
break;
}
} else {
if(s[curr]>s[prev]) {
currSub += s[curr];
}
}
count++;
}
if(currSub.length >= longestSub.length) {
longestSub = currSub;
}
};
return longestSub;
}
var result = substringChecker(s);;
console.log(result);
The funny thing it works great for all test cases I can come up with, but this one. The result should be "beggh" but it is "begg" instead. Why is the h not showing up, what am I missing?
The algorithm can be linear, I think you are overcomplicating it placing loops inside loops.
I would use something like
function substringChecker(s) {
var longestSub = "",
length = 0,
start = 0,
prev = s[0];
for (var i = 1; i <= s.length; ++i) {
if(i == s.length || s[i] < prev) {
if(length < i-start) {
longestSub = s.substring(start, i);
length = i-start;
}
start = i;
}
prev = s[i];
};
return longestSub;
}
document.write(substringChecker('azcbobobegghakl'));
first I made list of A-z
then check each letter and compare it with the next letter and save it in subString and...
function longest(str) {
//handle the case str is just one letter
if (str.length === 1) return str;
// create a list of alphabet A to Z
const alphabets = [...Array(26)].map(_ => String.fromCharCode(i++), (i = 97));
let longString = "";
let subSting = "";
for (let x = 0; x < str.length; x++) {
let char = str.charAt(x);
const nextChar = str.charAt(x + 1);
let charIndex = alphabets.findIndex(alphabet => alphabet === char);
let nextCharIndex = alphabets.findIndex(alphabet => alphabet === nextChar);
if (nextCharIndex >= charIndex) {
subSting = subSting + nextChar;
} else {
if (!subSting.length) {
subSting = subSting + char;
}
longString = subSting.length > longString.length ? subSting : longString;
subSting = "";
}
}
return longString;
}
console.log(longest("zyba"));
In my grid the column headers are named A,B,C...,AA,AB,AC,...etc like an excel spreadsheet. How can I convert the string to number like: A => 1, B => 2, AA => 27
Try:
var foo = function(val) {
var base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', i, j, result = 0;
for (i = 0, j = val.length - 1; i < val.length; i += 1, j -= 1) {
result += Math.pow(base.length, j) * (base.indexOf(val[i]) + 1);
}
return result;
};
console.log(['A', 'AA', 'AB', 'ZZ'].map(foo)); // [1, 27, 28, 702]
solution 1: best performance and browser compatibility
// convert A to 1, Z to 26, AA to 27
function lettersToNumber(letters){
var chrs = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ', mode = chrs.length - 1, number = 0;
for(var p = 0; p < letters.length; p++){
number = number * mode + chrs.indexOf(letters[p]);
}
return number;
}
solution 2: best performance and compatibility and shorter code (Recommended)
// convert A to 1, Z to 26, AA to 27
function lettersToNumber(letters){
for(var p = 0, n = 0; p < letters.length; p++){
n = letters[p].charCodeAt() - 64 + n * 26;
}
return n;
}
solution 3: short code (es6 arrow function)
// convert A to 1, Z to 26, AA to 27
function lettersToNumber(letters){
return letters.split('').reduce((r, a) => r * 26 + parseInt(a, 36) - 9, 0);
}
test:
['A', 'Z', 'AA', 'AB', 'ZZ','BKTXHSOGHKKE'].map(lettersToNumber);
// [1, 26, 27, 28, 702, 9007199254740991]
lettersToNumber('AAA'); //703
Here's a quick example of the code you should implement.
This will work with any given number of letters.
function letterToNumbers(string) {
string = string.toUpperCase();
var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', sum = 0, i;
for (i = 0; i < string.length; i++) {
sum += Math.pow(letters.length, i) * (letters.indexOf(string.substr(((i + 1) * -1), 1)) + 1);
}
return sum;
}
i just wrote a junk yard f##$ snippet... need to be optimized.. :)
charToNum = function(alpha) {
var index = 0
for(var i = 0, j = 1; i < j; i++, j++) {
if(alpha == numToChar(i)) {
index = i;
j = i;
}
}
console.log(index);
}
numToChar = function(number) {
var numeric = (number - 1) % 26;
var letter = chr(65 + numeric);
var number2 = parseInt((number - 1) / 26);
if (number2 > 0) {
return numToChar(number2) + letter;
} else {
return letter;
}
}
chr = function (codePt) {
if (codePt > 0xFFFF) {
codePt -= 0x10000;
return String.fromCharCode(0xD800 + (codePt >> 10), 0xDC00 + (codePt & 0x3FF));
}
return String.fromCharCode(codePt);
}
charToNum('A') => returns 1 and charToNum('AA') => returns 27;
// Given Column to Number
function colToNumber(str) {
let num = 0
let i = 0
while (i < str.length) {
num = str[i].charCodeAt(0) - 64 + num * 26;
i++;
}
return num;
}
//Given Number to Column name
function numberToCol(num) {
let str = '', q, r;
while (num > 0) {
q = (num-1) / 26;
r = (num-1) % 26
num = Math.floor(q)
str = String.fromCharCode(65 + r) + str;
}
return str;
}
I rewrote Yoshi's answer in a more verbose form that explains better how it works and is easier to port to other languages:
var foo = function(val) {
var base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var baseNumber = base.length;
var runningTotal = 0;
var characterIndex = 0;
var indexExponent = val.length - 1;
while( characterIndex < val.length ){
var digit = val[characterIndex];
var digitValue = base.indexOf(digit) + 1;
runningTotal += Math.pow(baseNumber, indexExponent) * digitValue;
characterIndex += 1
indexExponent -= 1
}
return runningTotal;
};
console.log(['A', 'AA', 'AB', 'ZZ'].map(foo)); // [1, 27, 28, 702]
Public Function ColLet2Num(Letras As String)
'RALONSO MAYO 2017
'A-> 1
'OQ ->407
'XFD->16384
Dim UnChar As String
Dim NAsc As Long
Dim F As Long
Dim Acum As Long
Dim Indice As Long
Letras = UCase(Letras)
Acum = 0
Indice = 0
For F = Len(Letras) - 1 To 0 Step -1
UnChar = Mid(Letras, F + 1, 1)
NAsc = Asc(UnChar) - 64
Acum = Acum + (NAsc * (26 ^ Indice))
Indice = Indice + 1
Next
If Acum > 16384 Then
MsgBox "La celda máxima es la XFD->16384", vbCritical
End If
ColLet2Num = Acum
End Function
const getColumnName = (columnNumber) => {
let columnName = "";
const alphabets = "abcdefghijklmnopqrstuvwxyz".toUpperCase();
while (columnNumber > 0) {
const rem = columnNumber % 26;
if (rem === 0) {
columnName += "Z";
columnNumber = columnNumber / 26 - 1;
} else {
columnName += alphabets[rem - 1];
columnNumber = Math.floor(columnNumber / 26);
}
}
return columnName.split("").reverse().join("");
};
console.log(getColumnName(27));
A good readability and performance example:
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// create dict to O(1) access to letter number
const dict = Object.fromEntries(letters.split('').map((it, index) => [it, index + 1]));
function toNumber(col) {
return col
.toUpperCase()
.split('')
.reduce((acc, letter, index) => acc + Math.pow(letters.length, col.length - (index + 1)) * dict[letter], 0);
}
Highly inspired by the different solutions put forth on this page
//fixed the one taken from here
function colToNumber(str: string): number {
var num = 0
for (var i = 0; i < str.length; i++) {
const current_letter = str.charCodeAt(i) - 64
const current_char = str[i]
if (i == str.length - 1) {
num += current_letter
} else {
var current = current_letter * Math.pow(26, str.length - i - 1)
num += current
}
}
return num;
}
//Given Number to Column name (taken from here)
function numberToCol(num: number) {
var str = '', q: number, r: number;
while (num > 0) {
q = (num - 1) / 26;
r = (num - 1) % 26
num = Math.floor(q)
str = String.fromCharCode(65 + r) + str;
}
return str;
}
function test_both() {
const dic = new Map<number, string>()
dic.set(1,"A")
dic.set(10,"J")
dic.set(13,"M")
dic.set(33,"AG")
dic.set(63,"BK")
dic.set(66,"BN")
dic.set(206,"GX")
dic.set(502,"SH")
dic.set(1003,"ALO")
dic.set(100,"CV")
dic.set(10111,"NXW")
dic.set(10001,"NTQ")
dic.set(9002,"MHF")
dic.set(5002,"GJJ")
dic.set(3002,"DKL")
dic.set(16384,"XFD")
for (var key of dic.keys()) {
const expected_a1 = dic.get(key) || ""
//console.log(`${ key }, ${ expected_a1 } `)
var actual = numberToCol(key)
var actual_num = colToNumber(expected_a1)
if (actual.localeCompare(expected_a1) != 0) {
console.error(`key = ${key} == expected=${expected_a1} actual = ${actual} `)
}
if (actual_num != key) {
console.error(`expected = ${expected_a1} key = ${key} == actual = ${actual_num} `)
}
}
}