This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 6 years ago.
How to create comma separated amount value in javascript?
For example, if I provide 123000.00 in textbox, the result should be 1,23,000.00
I tried the below function
function formatWithCommasAndDecimal(tempInputString,setvalue,decimalPointLen)
{
var inputString = "";
var beforeDecimal;
var afterDecimal = "00";
var newBeforeDecimal = "";
var commaCounter = 0;
if(tempInputString=="")
{
if(decimalPointLen=="8")
{
document.getElementById(setvalue).value="0.00000000";
}
else
{
document.getElementById(setvalue).value="0.00";
}
return false;
}
if(tempInputString!="0.00" || tempInputString!=" ")
{
if(tempInputString.indexOf(",")!='-1')
{
//Just remove all the commas
var len = tempInputString.length
for(i=0;i<len;i++)
{
if(tempInputString.charAt(i) != ",")
{
inputString = inputString + tempInputString.charAt(i);
}
}
}
else
{
tempInputString=parseFloat(tempInputString).toFixed(decimalPointLen);
inputString = tempInputString;
}
var tempArr = inputString.split(".");
//Format the portion before the decimal
beforeDecimal = tempArr[0];
for(i = beforeDecimal.length - 1;i>=0;i--)
{
newBeforeDecimal = newBeforeDecimal + beforeDecimal.charAt(i);
commaCounter++;
if(commaCounter % 3 == 0)
{
//Checking this so that the comma is not appended at the end
if(i > 0)
{
newBeforeDecimal = newBeforeDecimal + ",";
commaCounter = 0;
}
}
}
beforeDecimal = "";
for(i=newBeforeDecimal.length-1;i>=0;i--)
{
beforeDecimal = beforeDecimal + newBeforeDecimal.charAt(i);
}
//Format the portion after the decimal (if any is there)
if(tempArr.length != 1)
{
afterDecimal = tempArr[1];
}
var finalString = beforeDecimal + "." + afterDecimal;
document.getElementById(setvalue).value=finalString;
}
return finalString;
}
Related
I am trying to write a function that will validate that all entries within the commas are numberic and display "?" if they are not. for example: user enters 2,3,5b,c7 the output that I am getting is BCE? instead of BC?? This is the decode function that I am trying to validate in:
function fnDecode() {
var msg = $("textin").value;
if(msg === "") {
$("textin_span").innerHTML = "* Please enter a value to decode
*";
$("textin").focus();
return;
} else {
$("textin_span").innerHTML = "";
}
var nums = msg.split(","); //split method separates by delimiter
var outstr = ""; //out string
for (var i=0; i<nums.length; i++) {
var n2 = parseInt(nums[i]);
if (isNaN(n2)) { //if isNaN true, print ?
outstr += "?";
} else if (isNallN(nums[i])) { //THIS IS WHERE THE FN GOES
outstr += "?";
} else if (n2 === 0) {
outstr += " ";
} else if (n2 < 1 || n2 >26) {
outstr += "?";
}else {
outstr += String.fromCharCode(n2+64);
}
}
$("textout").value = outstr;
}
function isNallN(s) {
}
I corrected your fnDecode function.
You don't need multiple if to check for isNaN, !isNaN('5') will work as well as !isNaN(5). Check this Javascript Equality Table for more information.
Here, I adapted the function for it to work with a String given in
parameter and to return the wanted String.
function fnDecode(msg) {
var nums = msg.split(",");
var outstr = "";
for (num of nums) {
if (isNaN(num)) outstr += "?"; //isNaN works on "5" and 5
else if (+num === 0) outstr += " "; //We use +num to parse the String to an int
else if (+num < 1 || +num > 26) outstr += "?";
else outstr += String.fromCharCode(+num + 64);
}
return outstr;
}
var test = '1,2,3,4,5f,6r';
console.log(fnDecode(test));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is a shorter ES6 version :
function fnDecode(msg) {
return msg.split(',').map( num => isNaN(num) || (+num < 1 || +num > 26) ? '?' : +num == 0 ? ' ' : String.fromCharCode(+num + 64)).join('');
}
var test = '1,2,3,4,5f,6r';
console.log(fnDecode(test));
I am trying to get javascript to format phone numbers based on a users input of 10 or 11 digits. The 11 digits are for phone numbers that start with a 1 at the beginning like a 1-800 number. I need the final output to be either 000-000-0000 or 1-000-000-0000. The sample javascript code that I was given to start out with, works with the 10 digit phone number but I need the javascript to also recognize if there is a 1800 number and append accordingly.
The following is my initial working javascript and below that is code I found online that addresses the 10 and 11 digital formatting however I don’t know how to mesh the two together.
Thank you in advance for any help given.
~~~~~~~~~~~~~~~~~
<script type="text/javascript">
var phoneNumberVars = [ "UserProfilePhone", "UserProfilePhone1", "UserProfilePhone2", "UserProfilePhone3", ];
InitialFormatTelephone();
function InitialFormatTelephone()
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
FormatTelephone(phoneNumberVars[i]);
}
}
function StorefrontEvaluateFieldsHook(field)
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
if (field.id == "FIELD_" + FieldIDs[phoneNumberVars[i]])
{
FormatTelephone(phoneNumberVars[i]);
}
}
}
function FormatTelephone(varName)
{
var num = document.getElementById("FIELD_" + FieldIDs[varName]).value;
var charArray = num.split("");
var digitCounter = 0;
var formattedNum;
if (charArray.length > 0)
formattedNum = “-“;
else
formattedNum = "";
var i;
for (i = 0;i < charArray.length; i++)
{
if (isDigit(charArray[i]))
{
formattedNum = formattedNum + charArray[i];
digitCounter++;
if (digitCounter == 3)
{
formattedNum = formattedNum + “-“;
}
if (digitCounter == 6)
{
formattedNum = formattedNum + "-";
}
}
}
if (digitCounter != 0 && digitCounter != 10)
{
alert ("Enter a valid phone number!");
}
// now that we have a formatted version of the user's phone number, replace the field with this new value
document.getElementById("FIELD_" + FieldIDs[varName]).value = formattedNum;
// force an update of the preview
PFSF_AjaxUpdateForm();
}
function isDigit(aChar)
{
myCharCode = aChar.charCodeAt(0);
if((myCharCode > 47) && (myCharCode < 58))
{
return true;
}
return false;
}
</script>
<script type="text/javascript">
var phoneNumberVars = [ "UserProfilePhone", "UserProfilePhone1", "UserProfilePhone2", "UserProfilePhone3", ];
InitialFormatTelephone();
function InitialFormatTelephone()
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
FormatTelephone(phoneNumberVars[i]);
}
}
function StorefrontEvaluateFieldsHook(field)
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
if (field.id == "FIELD_" + FieldIDs[phoneNumberVars[i]])
{
FormatTelephone(phoneNumberVars[i]);
}
}
}
function FormatTelephone(varName)
{
var num = document.getElementById("FIELD_" + FieldIDs[varName]).value;
var cleanednum = num.replace( /[^0-9]/g, "");
var charArray = cleanednum.split("");
var digitCounter = 0;
var formattedNum = "";
var digitPos1 = 0;
var digitPos3 = 3;
var digitPos6 = 6;
if (charArray.length ===11)
{
digitPos1++;
digitPos3++;
digitPos6++;
}
if (charArray.length > 0)
formattedNum = "";
else
formattedNum = "";
var i;
for (i = 0;i < charArray.length; i++)
{
if (isDigit(charArray[i]))
{
formattedNum = formattedNum + charArray[i];
digitCounter++;
if (digitCounter === digitPos1)
{
formattedNum = formattedNum + "-";
}
if (digitCounter == digitPos3)
{
formattedNum = formattedNum + "-";
}
if (digitCounter == digitPos6)
{
formattedNum = formattedNum + "-";
}
}
}
if ((charArray.length ==10 || charArray.length == 11 || charArray.length == 0) === false)
{
alert ("Enter a valid phone number!");
}
// now that we have a formatted version of the user's phone number, replace the field with this new value
document.getElementById("FIELD_" + FieldIDs[varName]).value = formattedNum;
// force an update of the preview
PFSF_AjaxUpdateForm();
}
function isDigit(aChar)
{
myCharCode = aChar.charCodeAt(0);
if((myCharCode > 47) && (myCharCode < 58))
{
return true;
}
return false;
}
</script>
We get PDF's with the following formatted data.
14424, 14(100-103,706), 1488(zip 5-6,3),14(100-103,706,715,402-408,112),ect...
I need to take that data and parse it out to generate the given zip codes
14424,14100,14101,14102,14103,14706,14885,14886,14883
$('form').submit(function(e) {
$('textarea').val(parse_zip($('textarea').val()));
e.preventDefault();
});
function parse_zip(zip_codes) {
var valid = true;
var formated = zip_codes.replace(/[^\d()\-,]+/g, '');
var final_result = '';
/*if begins with digit*/
if (/^\d/.test(formated)) {
final_result = formated;
} else {
final_result = formated;
valid = false;
}
if (valid) {
return final_result;
} else {
return final_result + ' = Invalid';
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha256-7s5uDGW3AHqw6xtJmNNtr+OBRJUlgkNJEo78P4b0yRw= sha512-nNo+yCHEyn0smMxSswnf/OnX6/KwJuZTlNZBjauKhTK0c+zT+q5JOCx0UFhXQ6rJR9jg6Es8gPuD2uZcYDLqSw=="
crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha256-KXn5puMvxCw+dAYznun+drMdG1IFl3agK0p/pqT9KAo= sha512-2e8qq0ETcfWRI4HJBzQiA3UoyFk6tbNyG+qSaIBZLyW9Xf3sWZHN/lxe9fTh1U45DpPf07yj94KsUHHWe4Yk1A==" crossorigin="anonymous"></script>
<form>
<textarea class='form-control input-sm' rows="10">Before: 14424, 14(100-103,706), 1488(zip 5-6,3)</textarea>
<button type='submit'>
submit
</button>
</form>
<p class="help-block">
<br>Before: 14424, 14(100-103,706), 1488(zip 5-6,3)
<br>After: 14424,14100,14101,14102,14103,14706,14885,14886,14883
</p>
How can I parse this out?
EDIT
I have started on the parsing project, but I have come to a few stumbling blocks. here is what I have so far.
function rangeParser(zip_codes) {
var valid = true;
var formated = zip_codes.replace(/[^\d()\-,]+/g, '');
var final_result = '';
/*if begins with digit*/
if (/^\d/.test(formated)) {
var newString = '';
var openLeft = false;
for (var i = 0, len = formated.length; i < len; i++) {
if (formated[i] === '(') {
if (openLeft) {
/*if two left parentheses are open, then it's invalid*/
valid = false;
break;
} else {
openLeft = true;
}
} else if (formated[i] === ')') {
if (openLeft) {
openLeft = false;
} else {
/*if no left parentheses are open and you close it with a right parenthese, the it's invalid*/
valid = false;
break;
}
} else if (formated[i] === ',') {
if (openLeft) {
/*if you are between parentheses then use the '|' as a deliminator to be split latter*/
newString += '|';
} else {
newString += ',';
}
} else {
newString += formated[i];
}
}
if (valid) {
/*splits the string into seperate equations*/
var newArray = newString.split(',');
var append = '';
var substr = [];
var smsplit = [];
var addtome = [];
var addnext = '';
for (var i = 0, len = newArray.length; i < len; i++) {
if (/[^\d]/g.test(newArray[i])) {
if (/^\d/.test(newArray[i])) {
/*graps the appending digits*/
append = /^\d+/.exec(newArray[i])[0];
/*gets the string that will be parsed for generating automation*/
substr = newArray[i].substring(append.length).replace(/[^\d\-|,]+/g, '').split('|');
for (var j = 0, l = substr.length; j < l; j++) {
smsplit = substr[j].split('-');
if (smsplit.length === 2 && parseInt(smsplit[0]) < parseInt(smsplit[1])) {
if (parseInt(smsplit[0]) < parseInt(smsplit[1])) {
for (var k = parseInt(smsplit[0]), leng = parseInt(smsplit[1]); k < leng; k++) {
addnext = append + '' + k;
if (addnext.length === 5) {
addtome.push(addnext);
} else {
/*if zip is not 5 digits long, invalid*/
valid = false;
break;
}
}
} else {
/*if the ints are backwards, invalid*/
valid = false;
break;
}
} else if (smsplit.length === 1) {
addnext = append + '' + smsplit[0];
if (addnext.length === 5) {
addtome.push(addnext);
} else {
/*if zip is not 5 digits long, invalid*/
valid = false;
break;
}
} else {
/*if there are more than one dash, invalid*/
valid = false;
break;
}
if (!valid) {
break;
}
}
if (!valid) {
break;
}
} else {
/*if the string does not start with a digit, invalid*/
valid = false;
break;
}
} else if (newArray[i].length === 5) {
/*if it is a 5 digit number continue*/
addtome.push(newArray[i]);
continue;
} else {
/*if it has less or more than 5 digits and no special characters then it's invalid*/
valid = false;
break;
}
}
if (valid) {
final_result = uniq_fast(addtome).join(',');
}
}
} else {
valid = false;
}
if (valid) {
return final_result;
} else {
return formated + ' = Invalid';
}
}
function uniq_fast(a) {
var seen = {};
var out = [];
var len = a.length;
var j = 0;
for (var i = 0; i < len; i++) {
var item = a[i];
if (seen[item] !== 1) {
seen[item] = 1;
out[j++] = item;
}
}
return out.sort();
}
This is a rudimentary answer and I would love to see if someone can come up with a better answer than mine, that out preforms it.
$('#sub').click(function() {
$('textarea').val(rangeParser($('textarea').val()));
});
$('#re').click(function() {
$('textarea').val('Before: 14424, 14(100-103,706), 1488(zip 5-6,3)');
});
function rangeParser(zip_codes) {
var valid = true;
var formated = zip_codes.replace(/[^\d()\-,]+/g, '');
var final_result = '';
var invalidtext = '';
/*if begins with digit*/
if (/^\d/.test(formated)) {
var newString = '';
var openLeft = false;
for (var i = 0, len = formated.length; i < len; i++) {
if (formated[i] === '(') {
if (openLeft) {
/*if two left parentheses are open, then it's invalid*/
valid = false;
invalidtext = 'two left';
break;
} else {
openLeft = true;
newString += formated[i];
}
} else if (formated[i] === ')') {
if (openLeft) {
openLeft = false;
newString += formated[i];
} else {
/*if no left parentheses are open and you close it with a right parenthese, the it's invalid*/
valid = false;
invalidtext = 'no left';
break;
}
} else if (formated[i] === ',') {
if (openLeft) {
/*if you are between parentheses then use the '|' as a deliminator to be split latter*/
newString += '|';
} else {
newString += ',';
}
} else {
newString += formated[i];
}
}
if (valid) {
/*splits the string into seperate equations*/
var newArray = newString.split(',');
var append = '';
var substr = [];
var smsplit = [];
var addtome = [];
var addnext = '';
for (var i = 0, len = newArray.length; i < len; i++) {
if (/[^\d]/g.test(newArray[i])) {
if (/^\d/.test(newArray[i])) {
/*graps the appending digits*/
append = /^\d+/.exec(newArray[i])[0];
/*gets the string that will be parsed for generating automation*/
substr = newArray[i].substring(append.length).replace(/[^\d\-|,]+/g, '').split('|');
for (var j = 0, l = substr.length; j < l; j++) {
smsplit = substr[j].split('-');
if (smsplit.length === 2 && parseInt(smsplit[0]) < parseInt(smsplit[1])) {
if (parseInt(smsplit[0]) < parseInt(smsplit[1])) {
for (var k = parseInt(smsplit[0]), leng = parseInt(smsplit[1]); k <= leng; k++) {
addnext = append + '' + k;
if (addnext.length === 5) {
addtome.push(addnext);
} else {
/*if zip is not 5 digits long, invalid*/
valid = false;
invalidtext = 'ranged non five digit';
break;
}
}
} else {
/*if the ints are backwards, invalid*/
valid = false;
invalidtext = 'backwards range';
break;
}
} else if (smsplit.length === 1) {
addnext = append + '' + smsplit[0];
if (addnext.length === 5) {
addtome.push(addnext);
} else {
/*if zip is not 5 digits long, invalid*/
valid = false;
invalidtext = 'not five digit zip range';
break;
}
} else if (smsplit.length > 2) {
/*if there are more than one dash, invalid*/
valid = false;
invalidtext = 'more than one dash';
break;
}
if (!valid) {
break;
}
}
if (!valid) {
break;
}
} else {
/*if the string does not start with a digit, invalid*/
valid = false;
invalidtext = 'donst start with digit';
break;
}
} else if (newArray[i].length === 5) {
/*if it is a 5 digit number continue*/
addtome.push(newArray[i]);
continue;
} else {
/*if it has less or more than 5 digits and no special characters then it's invalid*/
valid = false;
invalidtext = 'non range not five digit';
break;
}
}
if (valid) {
final_result = uniq_fast(addtome).join(',');
}
}
} else {
/*if starting string doesn't have digit at first*/
invalidtext = 'begin non digit';
valid = false;
}
if (valid) {
return final_result;
} else {
return formated + ' = Invalid ' + invalidtext;
}
}
function uniq_fast(a) {
var seen = {};
var out = [];
var len = a.length;
var j = 0;
for (var i = 0; i < len; i++) {
var item = a[i];
if (seen[item] !== 1) {
seen[item] = 1;
out[j++] = item;
}
}
return out.sort();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<textarea class='form-control input-sm' rows="10">Before: 14424, 14(100-103,706), 1488(zip 5-6,3)</textarea>
<button id="sub">
submit
</button>
<button id="re">
Reset
</button>
<p class="help-block">
<br>Before: 14424, 14(100-103,706), 1488(zip 5-6,3)
<br>After: 14100,14101,14102,14103,14424,14706,14883,14885,14886
</p>
Here is the javascript code:
I need help getting the word to display after the player looses.
var can_play = true;
//this is the array of words
var words = new Array("VALIDATE", "DESIGN", "INPUT", "ARRAY", "OBJECT", "DOCUMENTATION", "JQUERY", "CALCULATE", "ABSOLUTE", "DREAMWEAVER", "BROWSER", "HTML", "CONCATINATION");
var display_word = "";
var used_letters = "";
var wrong_guesses = 0;
//this will allow the letters to be entered in only 1 time
function selectLetter(l) {
if (can_play == false) {
return;
}
if (used_letters.indexOf(l) != -1) {
return;
}
used_letters += l;
document.game.usedLetters.value = used_letters;
if (to_guess.indexOf(l) != -1) {
// this will display the correct letter guesses
pos = 0;
temp_mask = display_word;
while (to_guess.indexOf(l, pos) != -1) {
pos = to_guess.indexOf(l, pos);
end = pos + 1;
start_text = temp_mask.substring(0, pos);
end_text = temp_mask.substring(end, temp_mask.length);
temp_mask = start_text + l + end_text;
pos = end;
}
display_word = temp_mask;
document.game.displayWord.value = display_word;
if (display_word.indexOf("*") == -1) {
// this will display a message if you win
$('#win').html("Well done, you won!");
can_play = false;
}
} else {
// this will display the incorrect letter guesses
wrong_guesses += 1;
$('#wrong_guesses').html(wrong_guesses);
if (wrong_guesses == 6) {
// this will display a message if you loose
$('#win').html("Sorry, you have lost!");
can_play = false;
}
}
}
//this will reset the game to play again
function reset() {
selectWord();
document.game.usedLetters.value = "";
guessed_letters = "";
wrong_guesses = 0;
$('#win').html("");
$('#wrong_guesses').html("");
}
//this will have the computer select a word from my array
function selectWord() {
can_play = true;
random_number = Math.round(Math.random() * (words.length - 1));
to_guess = words[random_number];
// this will display mask
masked_word = createMask(to_guess);
document.game.displayWord.value = masked_word;
display_word = masked_word;
}
function createMask(m) {
mask = "";
word_length = m.length;
for (i = 0; i < word_length; i++) {
mask += "*";
}
return mask;
}
$('#win').html("Sorry, you have lost, the word was " + to_guess + "!");
You assigned the to be guessed word here:
to_guess = words[random_number];
You would learn much from posting your code to Code Review.
I have a form that I'm using to calculate some numbers, and the final 3 input fields on the form are disabled because they show the results of the calculator.
I'm using the following javascript/jquery to add commas to the user editable fields which works great but I can't seem to find a way to add commas to the "results" fields:
$('input.seperator').change(function(event){
// skip for arrow keys
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var $this = $(this);
var num = $this.val().replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
// the following line has been simplified. Revision history contains original.
$this.val(num2);
});
function RemoveRougeChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
This is what I'm using the populate the fields, basically the fields show the results in dollars, so I'm trying to add a comma every 3 numbers:
$('#incorrect-payment').val(fieldK);
$('#correcting-payment').val(fieldL);
$('#total-cost').val(fieldM);
I think you'd want to use a function like this:
function FormatCurrency(amount, showDecimals) {
if (showDecimals == null)
showDecimals = true;
var i = parseFloat(amount);
if (isNaN(i)) { i = 0.00; }
var minus = false;
if (i < 0) { minus = true; }
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
if (showDecimals) {
if (s.indexOf('.') < 0) { s += '.00'; }
if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
}
//s = minus + s;
s = '$' + FormatCommas(s, showDecimals);
if (minus)
s = "(" + s + ")";
return s;
}
function FormatCommas(amount, showDecimals) {
if (showDecimals == null)
showDecimals = true;
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 (!showDecimals) {
amount = n;
}
else {
if (d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
}
amount = minus + amount;
return amount;
}
May be you might want to trigger change event manually through javascript for your three read-only input fields. Using jquery trigger . I am not sure but it seems like a bad idea to have a read-only input field if no user can change these values. Usually having read-only input fields is good if a user with some security can edit those and some cannot.