Sometimes in a HTML file, we have a <p> tag that shows the price of a product. For example the price is "1,200,000 Dollar". Now a user added this product to the cart. I want that the webpage display the total price in the cart.
Now in JavaScript I want the program separate the number of price from string and put that in a variable. Here in the example that I said the <p> tag shows "1,200,000 Dollar". Now I want to put just the number(in the example the number is 1,200,000) in a variable to calculate the total price later.
What should I do?
You can also use a split function in this case.
const currencyString="1,000,000 Dollars";
const currencyNumber=Number(currencyString.split(' ')[0].replace(/,/g, ''));
Does the below answer your question...
var input = '1,200,000 Dollar';
var output = Number(input.replace(/[^0-9\-\.]/g, ''));
First we remove all non-digit characters with .replace method and then create a new Number value.
A few other usage examples:
function stringToNumber(string) {
return Number(string.replace(/[^0-9\-\.]/g, ''));
}
var inputs = [
'1,000,000 Dollars',
'$1,000,000.50',
'-50.12 USD'
];
for (var i = 0; i < inputs.length; i++) {
console.log(inputs[i], stringToNumber(inputs[i]));
}
Related
I have a html textarea element in my page where user gives comma separate values. for example below.
A-48402,AA,SBAFL,AA+,USD,,
From javascript (which I prefer) I am applying logic to check if the last row value is blank (separated by comma only) then to put a String value 'Y'. Thus I am writing the below
var data = document.getElementById('txid').value;
rows = data.split('\n');var row1 = rows[0];row1Values=row1 .split(',');
Then I am applying logic to verify whether the last value for every row is blank or not, which is actually blank, then adding the below.
row_values.push('Y');
It is reflecting in debugger.
But what I see is the value 'Y' in the Java action class is not reflecting and showing usual 'Y' while the page submit. How can I add this value 'Y' in every rows end (where there is blank) so that it will be visible in action class?
String Data = request.getParameter('mbs_inst_data');
This data is populated with the same blank values.
If you're only checking for the last row then the only case that would happen is when it's ,,
so you can just do a simple check
let data = 'A-48402,AA,SBAFL,AA+,USD,,'
data = data.split(',')
let lastRowIsBlank = data[data.length-2] === ""
// we are doing length - 2 because in your situation we have 2 ""
// since you have two commas. If you have only 1 comma we would
// the same steps but with length - 1
if(lastRowIsBlank) data[data.length-2] = "Y"
return data.toString()
You can use it like this.
<p id="demo">Visit Microsoft! ,,</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace(/,,$/, ',Y');
document.getElementById("demo").innerHTML = res;
}
</script>
Output
Visit Microsoft! ,Y
I guess this would help you.
I need some assistance figuring out how to sum a column of dynamic totals that could be a positive or negative dollar amount, or an indication of stock shares.
I have a tab-delimited text file of donor contributions for that I am matching up against a CSV file of other related customer data that I am using to create a statement letter which will show a "donation history" of a particular donor. Each donor has a different amount of donations, and to complicate things, the column of data for a particular donation record could show either "$1,000.00" or "($1,000.00)" or "2 Shares APPL". The number with the parentheticals is of course, representing a negative number.
At the end of this column, I need to show a string that will read either "Total: $1,000.00," or if any of the donation history contains a donation record that included shares of stock the returned string will simply read, "$1,000.00 & Stock."
I have been racking my brain trying to come up with the JS rule that can achieve this. I have the JS rule that is generating the donation history correctly, but summing the donation amount column is causing me to go crazy...
Here is the JS for generating my donation history list in the letter (this seems to be working fine):
var contributionList = new ExternalDataFileEx("/~wip/248839 Frontiers/Master Data/Double Data proof.txt", "\t");
var donor_id = Field("Supporter");
var lb = "<br>\n";
var matches = new Array();
for (var i = 0; i <= contributionList.recordCount; i++) {
var idVariable = contributionList.GetFieldValue(i, "Supporter");
var dateVariable = contributionList.GetFieldValue(i, "Donation Date");
var ministryVariable = contributionList.GetFieldValue(i, "Ministry Designation");
var giftVariable = contributionList.GetFieldValue(i, "Donation Amount");
var tsSettings = "<p tabstops=19550,Right,,;29600,Left,,;>";
var ts = "<t>";
if (donor_id == idVariable)
matches.push(tsSettings + dateVariable + ts + giftVariable + ts + ministryVariable);
}
//return matches;
return matches.join(lb);
Now here is the JS code that is not working just fine. I am trying to tally the donation amount column, it only returns "Total: $0.00 & Stock" every time (I have tried to explain my thought process via comments):
var contributionList = new ExternalDataFileEx("/~wip/248839 Frontiers/Master Data/Double Data proof.txt", "\t");
var donor_id = Field("Supporter");
for (var i = 0; i <= contributionList.recordCount; i++) {
var idVariable = contributionList.GetFieldValue(i, "Supporter");
var giftVariable = contributionList.GetFieldValue(i, "Donation Amount");
var sum = 0;
var shares = 0;
var tsSettings = "<p tabstops=19550,Right,,;29600,Left,,;>";
var ts = "<t>";
var totalStr = "Total ";
var stockStr = " & Stock";
var totalFormatted = FormatNumber("$#,###.00", Math.max(0, StringToNumber(sum)));
// Match data from linked file to current Supporter
if (donor_id == idVariable) {
// Look at current record and see if it contains the word "Share(s)"
// or not and act accordingly
if (giftVariable.match(/(^|\W)share($|\W)/i) || giftVariable.match(/(^|\W)shares($|\W)/i)) {
// Turn switch "on" if donation amount is a share or shares so
// we can have the " & Stock" appended to our string.
shares = 1;
// Because this donation is/are shares, we must "zero" this
// amount to make the math work when we sum everything up...
giftVariable = 0;
// This is where we are keeping our running total...
sum += giftVariable[i];
} else {
// This record was not a donation of share(s) so we now have to
// determine whether we are dealing with postive or negative numbers
// and then strip out all of the non-number characters, remove and
// replace the () whis just a "-," leaving us with a number we can
// work with...
// If number has parenthesis, then deal with it...
if (giftVariable.indexOf("(")) {
// Strip out all the ()$, characters...
giftVariable = giftVariable.replace(/[()$,]/g,"")
// Append the minus sign to the number...
giftVariable = "-" + giftVariable;
sum += giftVariable[i];
} else {
giftVariable = giftVariable.replace(/[$,]/g,"");
sum += giftVariable[i];
}
}
}
}
// Return Total...
if (shares == 1) {
return tsSettings + totalStr + ts + totalFormatted + stockStr;
} else {
return tsSettings + totalStr + ts + totalFormatted;
}
Any assistance would be greatly appreciated!
The problem (and code) needs to be broken into smaller, atomic steps. From your description it sounds like you should:
load a text file into memory
for each line in the file
extract: {
donor_id
charity
gift
and store the results in a contributions dictionary
for each item in the contributions dictionary
transform gift string into {
dollarAmount: float with a default of 0.0
stock: name with a default of ""
}
create an empty dictionary called totals
each item will have the shape {
id
dollarAmount as a float
stocks an an array
}
for each item in the contributions dictionary
lookup the id in the totals dictionary
if it exists
totals[id].dolarAmount += item.dollarAmount
totals[id].stocks.push(item.stock)
otherwise
totals[id].dollarAmount = item.dollarAmount
totals[id].stocks = [item.stock]
normalize your charities
for each item in totals dictionary
remove any empty strings from item.charities
create your report
for each item in totals dictionary
write`${item.id} donated `${item.dollarAmont}` ${item.stocks.length > 1 ? 'and stock' : ''
I believe you are trying to do too many things at once. Instead, the goal should be to normalize your data before you attempt to perform any calculations or aggrgrations, then normalize your aggregrations before writing your summaries or reports.
I would also stay away from using any direct string manipulation. You should have a dedicated function whose only purpose is to take a string like "($20.34) and 1 share of APPL" and return either 20.34, -20.34, or 0.0. And a different function whose only purpose is to take the same string and return either true or false is stock was present.
I have 5 inputs that have prices in them. There is a sixth input that will display the total price by adding the prices of the first five inputs together.
function calculateTotal(){
var priceInputs = document.querySelectorAll("input[name^='tPriceInput']");
var totalPrice = 0;
for(var i = 0; i < priceInputs.length; i++){
totalPrice = totalPrice + parseInt(priceInputs[i].value);
}
return totalPrice;
}
The function above always returns NaN... Why does this not work? I have also tried without the parseInt method but that only adds the strings together.
There is not enough info but I assume from all you have said you use commas , in the price as a delimeter instead of dots ., but JavaScript requires dots. This is a common problem for non-english regional settings.
If so, try this:
totalPrice = totalPrice + parseInt(priceInputs[i].value.replace(",", "."));
change
var priceInputs = document.querySelectorAll("input[name^='tPriceInput']");
to
var priceInputs = document.querySelectorAll("input[name='tPriceInput']");
i am relatively new to stackoverflow and have searched for some time for an answer to my question. I found some links like this one How to split a comma-separated string?
but still can't quite understand what I am doing wrong with my short little javascript program.
Anyway here it is. Help would be appreciated.
I basically am trying to create a prompt that asks the user to input 3 numbers seperated by commas, then change that string into an array so that I can multiply the values later on. So far, when i try to console.log this my results are as follows : 1,2
It doesn't print out the third digit(3rd number entered by the user).
var entry = prompt("Triangle side lengths in cm (number,number,number):")
if(entry!=null && entry!="") {
entryArray = entry.split(",");
for (i=0; i<3; i++)
{
entryArray[i] = entry.charAt([i]);
}
}
console.log(entryArray[0] + entryArray[1] + entryArray[2]);
Split creates an array already. So, if you enter 1,2,3, you get an array like this when you split it: ["1", "2", "3"]. In your for loop, you are getting the characters from the original input, not your array. In order to add them, you need to change the input to numbers since they are considered strings. So your for loop should look like this:
for (i=0; i<3; i++)
{
entryArray[i] = parseFloat(entryArray[i]);
}
overwriting the strings with the digits.
Try
for (i=0; i<3; i++)
{
entryArray.push(parseInt(entryArray[i]);
}
You can remove the body of the for。like this:
var entry = prompt("Triangle side lengths in cm (number,number,number):")
console.log(entry);
if(entry!=null && entry!="") {
entryArray = entry.split(",");
console.log(entryArray);
}
console.log(entryArray[0] + entryArray[1] + entryArray[2]);
try this code, i removed your looping which was overwriting the array.
var entry = prompt("Triangle side lengths in cm (number,number,number):");
if(entry!=null && entry!="") {
entryArray = entry.split(",");
console.log(entryArray[0] + entryArray[1] + entryArray[2]);
}
I need a JavaScript function that will parse the HTML source of the page from which it is called as an external script, retrieve any dollar amounts in the source, and set the highest dollar amount to a JavaScript variable.
So for instance, if the page contains the text, "Your product is $40.32 and tax is $4.50, your total is $44.82.", the JS should parse those values and set $44.82 to "var total" as the highest amount. Possible?
Thanks based on the tips I wrote this, which works. Hopefully yours or my solution will help others:
var dochtml = document.getElementsByTagName('body')[0].innerHTML;
dochtml = dochtml.replace(/(\r\n|\n|\r)/gm,"");
var price_array = new Array;
var pattmatch = /(\$(([0-9]{0,1})?.[0-9]{1,2}))|(\$([1-9]{1}[0-9]{0,2}([,][0-9]{3})*)(.[0-9]{1,2})?)/gi;
price_array = dochtml.match(pattmatch);
if (price_array) {
for (var i=0; itotal || !total) {
var total=price_array[i];
}
}
document.write(total);
}
You can grab the HTML of the current document from the Javascript by grabbing the document's innerHtml, something like:
document.getElementsByTagName('html')[0].innerHTML
Then you can pull out all the currency values with a regular expression, something like:
((\$(([0-9]{0,1})?\.[0-9]{1,2}))|(\$([1-9]{1}[0-9]{0,2}([,][0-9]{3})*)(\.[0-9]{1,2})?))
Just loop through all the matches and every time the current match is greater than the value in total, set total to the current match.
Disclaimer: That regex was pulled from the community on http://gskinner.com/RegExr/ and I can't promise you it's 100% fullproof.
Take a look at this question here, which demonstrates how to extract numbers from a String: Javascript extracting number from string
Try this:
// get all content from page
var content = document.body.innerHTML;
// create an array of all dollar amounts in the content
arrayNum = content.match(/\$[0-9]+\.[0-9]+/g);
// display array of numbers
console.info(arrayNum);
var high = 0;
for(var i = 0; i < arrayNum.length; i++) {
// remove the dollar sign and cast the string to a float
arrayNum[i] = parseFloat(arrayNum[i].substring(1));
// get the high value - O(n) operation
high = ( (arrayNum[i]) > high ) ? arrayNum[i] : high;
}
alert("High value = " high);