I'm trying to understand how to user parseFloat to convert a string to a number--which by the way changes based on a users rewards club points.
Here's the code I've written so far:
var ptsBalance = jQuery('.value.large.withCommas').text(); // get current RC points balance
var strParse = parseInt(ptsBalance, 10); // * Output should be current RC balance
alert(strParse); // alert Rewards Club Balance
var bonusPoints = 70000;
var totalPts = jQuery(strParse + bonusPoints); // sum total of Bonus and Current points
jQuery(strParse).appendTo('.currentPts');
jQuery(totalPts).appendTo('.totalPts'); // insert RC points balance after 'Current Points' text
Clearly I'm not using pareFloat, but rather strParse, which is rounding my string. That said, how do I convert a string to a number that could be "10", "100", "1,000", "10,000" etc.?
Here's a link to my Fiddle: http://jsfiddle.net/bkmills1/60vdfykq/
Still learning...
Thanks in advance!
In your fiddle, change line 4 from:
var strParse = parseInt(ptsBalance, 10);
to
var strParse = parseInt(ptsBalance.replace(',',''), 10);
You may also want to remove any other symbols needed, or even use regular expressions to do just that.
Related
Since I could not make .toFixed(2) to work I designed my own piece of code to add desired decimal digits after the "." by simple joining two strings with + sign.
While Browser.msgBox outputs the 2 strings joined correctly as "1.00",
it seems like getRange.setValue outputs only the first of the 2 strings as "1" :(
function myFunction() {
var ss_calc = SpreadsheetApp.openById("1cFt0DbnpWGHquKk4ijxdKhwkaF8GhumWDWjTpHuSXbQ");
var sheet_calc = ss_calc.getSheetByName("Calcs");
var ss_source = SpreadsheetApp.openById("1gXeXmiw9EnzQXaiE7H8_zrilE2zyotlSuuIS8X9IxfQ");
var sheet_source = ss_source.getSheetByName("Farmah");
var decDig = ""; var strDec = ""; var impVal = "";
impVal = sheet_source.getRange(12,7).getValue().toString();
if (JSON.stringify(impVal).indexOf(".")>-1)
{ if (JSON.stringify(impVal).split(".")[1].length < 2 )
{
if (JSON.stringify(impVal).split(".")[1].length < 1)
{
decDig = "00";
}
else
{
decDig = "0";
}
}
}
else
{
decDig = ".00";
}
var strDec = impVal.toString() + decDig.toString();
Browser.msgBox(JSON.stringify(impVal).indexOf(".")+ "\\n" +
impVal.toString()+ "\\n" +
decDig+ "\\n" +
strDec);
sheet_calc.getRange(1,1).setValue(strDec);
}
From sheet_calc.getRange(1,1).setValue(strDec); I am expecting to get output "1.00" but I get only "1" :(
What am I missing?
Here are the links to google spreadsheets ( anyone with the link can edit :)
(above code has to be triggered manually by script editor in the first spreadsheet here under):
https://docs.google.com/spreadsheets/d/1cFt0DbnpWGHquKk4ijxdKhwkaF8GhumWDWjTpHuSXbQ/edit?usp=sharing
https://docs.google.com/spreadsheets/d/1gXeXmiw9EnzQXaiE7H8_zrilE2zyotlSuuIS8X9IxfQ/edit?usp=sharing
You want to put the value of 1.00 to a cell "A1".
If my understanding is correct, how about this modification? I think that the reason of your issue is that the value by putting by setValue() is converted to the number. By this, 1 is shown. In order to put the value as 1.00, I think that there are 3 patterns. Please select one of them for your situation.
Pattern 1:
In this pattern, from your question, the value is put as a string using setNumberFormat("#").
From:
sheet_calc.getRange(1,1).setValue(strDec);
To:
sheet_calc.getRange(1,1).setNumberFormat("#").setValue(strDec);
Pattern 2:
In this pattern, from your question, the format of cell is set using setNumberFormat("0.00").
From:
sheet_calc.getRange(1,1).setValue(strDec);
To:
sheet_calc.getRange(1,1).setNumberFormat("0.00").setValue(strDec);
Pattern 3:
In this pattern, from the script of your shared Spreadsheet, When decDig is ".00", the format is set.
From:
sheet_calc.getRange(x+6,c).setValue(strDec);
To:
var range = sheet_calc.getRange(x+6,c);
if (decDig) {
range.setNumberFormat("0.00").setValue(strDec); // or setNumberFormat("#")
} else {
range.setValue(strDec);
}
Reference:
setNumberFormat(numberFormat)
If I misunderstood your question and this was not the result you want, I apologize.
From sheet_calc.getRange(1,1).setValue(strDec); I am expecting to get output "1.00" but I get only "1" :(
Google Sheets, as well as other spreadsheet apps, have an automatic data type assignation, so things that look as numbers are converted to Google Sheets number data type, etc.
You could prepend an ' to force that a value be treated as text or you could set the number format in such way that numbers are displayed with two decimals. The cell formatting could be applied in advance, i.e., by using the Google Sheets UI commands or you could use Apps Script to set the format for you.
I'm not sure how to word the question and i'm still quite new at javascript.
So I've got a random quote generator that has each quote result as an array. I'd like to add in two items in the array which I've got so far but having one result be a random number generated eg "2 quote" but having 2 be randomised each time. The end result is for a browser based text game. So it could be "2 zombies attack" or "7 zombies attack." The code I have so far is:
var quotes = [
[x, 'Zombies attack!'],
[x, 'other creatures attack'],
['next line'],
]
function newQuote() {
var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quote').innerHTML = quotes[randomNumber];
}
Ideally need x(or i however it's going to work) to be the result of a random number between a set range, each differently each array.
Thank you
p.s I forgot to mention that not all the quotes require a number. Thats why I've done it as a double array.
If I understand your goal correctly, you want to have a set of similar-ish message templates, pick one of them at some point and fill it with data, correct? There's a lot of ways to tackle this problem, depending on how varying can your templates be. For a simple case in my head where you just need to prepend a number to a string I'd do something like this:
var messages = [" zombies attack",
" other creatures attack"], // define your messages
messageIndex = Math.floor(Math.random() * messages.length), // pick one of them
numberOfMonsters = Math.floor(Math.random() * 10 + 1), // get your random number
result = numberOfMonsters + messages[messageIndex]; // construct a resulting message
document.getElementById('quote').textContent = result;
If you'd rather have more complex strings where you don't necessarily add a number (or any string) to the beginning, like ["There's X things in the distance", "X things are somewhere close"], then I'd recommend to either come up with some sort of string formatting of your own or use a library to do that for you. sprintf.js seems to be just right for that, it will let you do things like this:
var messages = ["%d zombies attack",
"A boss with %d minions attacks"], // define your messages
messageIndex = Math.floor(Math.random() * messages.length), // pick one of them
numberOfMonsters = Math.floor(Math.random() * 10 + 1), // get your random number
result = sprintf(messages[messageIndex], numberOfMonsters) // format a final message
document.getElementById('quote').textContent = result;
EDIT: Your task is much more complex than what is described in the original question. You need to think about you code and data organization. You have to outline what is finite and can be enumerated (types of actions are finite: you can loot, fight, move, etc.), and what is arbitrary and dynamic (list of monsters and loot table are arbitrary, you have no idea what type and amount of monsters game designers will come up with). After you've defined your structure you can come up with some quick and dirty message composer, which takes arbitrary entities and puts them into finite amount of contexts, or something. Again, I'm sort of shooting in the dark here, but here's an updated version of the code on plunkr.
I solved it to do what I want and still have the numbers different. The issue was I should have had the number generator within the quote function. Also can create multiple variables to use too for different number generators. The plan is to then integrate it with php to add content dynamically. Which I can do. Thanks Dmitry for guiding me in the right direction.
function newQuote() {
var MonsterOne = Math.floor((Math.random() * 14) + 0);
var MonsterTwo = Math.floor((Math.random() * 14) + 0);
var MonsterThree = Math.floor((Math.random() * 14) + 0);
var MonsterFour = Math.floor((Math.random() * 14) + 0);
var quotes = [
['Test', MonsterOne, 'One'],
['Test', MonsterOne,'Two'],
['Test', MonsterThree, 'Three'],
[MonsterFour, 'Four'],
['Five'],
]
var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quote').innerHTML = quotes[randomNumber];
}
I am doing an odds comparison site, What I'd like to do is get the value i.e 13/2 and do the maths as in 13 Divided 2 = 6.5
Then I'd like to tag the 6.5 on as a data-odds-decimal value on a button.
My jQuery is looping each class, But not doing the necessary maths.
My HTML code is as follows :
<button class="odds-btn" data-odds-fractional="13/2">13/2</button>
<button class="odds-btn" data-odds-fractional="2/5">2/5</button>
<button class="odds-btn" data-odds-fractional="1/2">1/2</button>
So for each data-odds-fractional I need to do the maths of 13/2, 2/5, 1/2 to then return the decimal value.
My current jQuery is as follows...
$('.odds-btn').each(function()
{
// Get The Decimal Value...
var odds_decimal = $(this).attr('data-odds-fractional');
// Add The Fractional Value as a new attr...
var odds_fractional = odds_decimal;
$(this).attr('data-odds-decimal', odds_fractional);
})
The data-odds-decimal is just coming back as the fractional value, Can I get jQuery to force do the maths or any other way?
Cheers
You can't make jQuery do a calculation like that, it will only do simple parsing when reading the data values.
Split the string and do the calculation:
var parts = odds_decimal.split('/');
var odds_fractional = parseInt(parts[0], 10) / parseInt(parts[1], 10);
I have a function with info that grabs hours, rates, and then tax deduction and then spits it out. It works fine
var newtax= new Number(dep[i]);
taxrate = newtax*100;
var h=eval(document.paycheck.hours.value);
var r=eval(document.paycheck.payrate.value);
document.paycheck.feedback.value= taxrate + txt;
var total= r*(1-newtax)*h ;
total=total.toFixed(2);
document.paycheck.feedback3.value= ("$ "+ total);
I have to put where it takes the total and puts it in a function to put it only two decimals. It works this way and only does two decimals but i need the decimal conversion in a function. can anyone shed some like .
This is where i cut it to two decimals and i am unable to put in function and then send it back to the feedback3.value.
total=total.toFixed(2);
document.paycheck.feedback3.value= ("$ "+ total);
If you're asking how to write a function that takes a number and formats it as a dollar value with two decimals (as a string) then this would work:
function formatMoney(num) {
return "$ " + num.toFixed(2);
}
// which you could use like this:
document.paycheck.feedback3.value= formatMoney(total);
// though you don't need the total variable (unless you use it elsewhere)
// because the following will also work:
document.paycheck.feedback3.value = formatMoney( r*(1-newtax)*h );
By the way, you don't need eval to get the values from your fields. Just say:
var h = document.paycheck.hours.value;
var r = document.paycheck.payrate.value;
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);