I'm making a conversion app and I keep getting return Not a Number (NaN)
function conversion() {
var bill = document.getElementById('bill');
var mates = document.getElementById('mates');
console.log(bill);
console.log(mates);
var pay = parseInt(bill)/parseInt(mates);
alert("Each mate pays: " + pay);
}
Can't figure out why it won't return in integer.
You're trying to parse an HTML Element into an integer. What you probably want is to get the values from the inputs:
var bill = document.getElementById('bill').value;
var mates = document.getElementById('mates').value;
you need to get the values, now you are parsing entire elements.
function conversion() {
var bill = document.getElementById('bill').value; // <---
var mates = document.getElementById('mates').value; // <---
console.log(bill);
console.log(mates);
var pay = parseInt(bill)/parseInt(mates);
alert("Each mate pays: " + pay);
}
Related
I am calculating 2 fields on a form with values but it seems in some cases it's not working. Here's my javascript. I am adding $oneTimeCostField and $recurringTotalCostField to get the value into the $totalRetailAmountField. Here's the result I am getting when I add say 1,555.00 + 566.00 = the value is 567.00 (?). Any idea what I'm doing wrong? In some cases it works correctly when the values are lower. Thanks, just stumped
var $recurringCostField = $('#am_attribute_campaign_addon_monthly_cost_value');
var $recurringTotalCostField = $('#am_attribute_campaign_addon_total_monthly_cost_value');
var $totalRetailAmountField = $('#am_oie_string_total_monthly_cost_value');
var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');
function calcVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseFloat(num1) + parseFloat(num2);
if (!isNaN(result)) {
$totalRetailAmountField.val(result.toFixed(2));
}
}
calcVal();
$oneTimeCostField.on("keydown keyup", function() {
calcVal();
});
$recurringTotalCostField.on("keydown keyup", function() {
calcVal();
});
You need to remove the commas before parsing:
var result = parseFloat(num1.replace(/,/g, '')) + parseFloat(num2.replace(/,/g, ''));
similiar question on this link
Remove commas from the string using JavaScript
That is because parseFloat() converts the string "1,555.00" to the number 1.
To convert it to a proper floating point number, it needs to include a single dot only.
console.log(parseFloat("1.555"));
I built an app that I then built with PhoneGap Build.THe purpose is for it to run a code (starts at var Quotes once per day when the app is loaded).
When debugging why it wasn't working I noticed that in console I was getting back my message "Local storage didn't work". This means that my initial localstorage.getItem which is supposed to make sure the local storage can be read is returning null. So my code never gets executed.
What am I doing wrong?
function onDeviceReady() { //Do something when the app on device is loaded
var localVal = localStorage.getItem('DateOpened');
if(localVal == null){
console.log("LocalStorage did not work...")}
else
{
var tempd = new Date(); //Get today's date
var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear();
if(localVal.localeCompare(str) == -1)
{
var Quotes = [];
var ID = [];
var Tag = [];
var seen = [];
localStorage.setItem('DateOpened',str);
console.log("The App Ran, you can get a new fat tomorrow");
console.log("Todays date:" + str);
}
}
}
Initially, there will be no DateOpened item in local storage, so your code will follow the "did not work" branch, because getItem returns null for things that don't exist. That branch never sets anything in DateOpened, so...you'll always follow that branch.
The fix is not to skip over your code setting DateOpened if the device has local storage.
There's also an unrelated problem: Your var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear() does not produce a string, it produces a number formed by adding those values together, since they're all numbers. Your later localeCompare will fail because it's not a string. You also have the fields in the wrong order for a meaningful textual comparison — you need year first, then month, then day.
Here's a minimal fix, see comments:
function onDeviceReady() {
var tempd = new Date();
// Note that by adding strings in there, we end up with a string instead of adding.
// Note the order: Year first, then month, then day.
// Also, since we display it, we put separators in and add 1 to month (since Jan = 0).
var str = tempd.getFullYear() + "-" + (tempd.getMonth() + 1) + "-" + tempd.getDay();
var localVal = localStorage.getItem('DateOpened');
// If we have no stored value, or it's more than a day old by your definition,
// do your stuff and store the new date
if (localVal == null || localVal.localeCompare(str) < 0) {
var Quotes = [];
var ID = [];
var Tag = [];
var seen = [];
localStorage.setItem('DateOpened', str);
console.log("The App Ran, you can get a new fat tomorrow");
console.log("Todays date:" + str);
}
}
I think this is help full for you.
function onDeviceReady() { //Do something when the app on device is loaded
var localVal = localStorage.getItem('DateOpened');
if (typeof(DateOpened) == "undefined")
console.log("LocalStorage did not work...")}
else
{
var tempd = new Date(); //Get today's date
var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear();
var allRecords=JSON.parse(localStorage.getItem("DateOpened"));
if(allRecords == -1)
{
var Quotes = [];
var ID = [];
var Tag = [];
var seen = [];
localStorage.setItem('DateOpened',str);
console.log("The App Ran, you can get a new fat tomorrow");
console.log("Todays date:" + str);
}
}
}
How do I add the following text boxes together with the logic below?
oneTextBox = $120.00,
twoTextBox = .03*oneTextBox,
threeTextBox = oneTextBox + twoTextBox
I would also like the units of each text box to be in dollars ($).
function doGet(e) {
var app = UiApp.createApplication();
var VertPanel = app.createVerticalPanel().setId('VertPanel');
var oneTextBox = app.createTextBox().setText("$120.00").setId("oneTextBox").setName("oneTextBox");
var twoTextBox = app.createTextBox().setId("twoTextBox").setName("twoTextBox");
var threeTextBox = app.createTextBox().setId("threeTextBox").setName("threeTextBox");
app.add(VertPanel);
VertPanel.add(oneTextBox).add(twoTextBox).add(threeTextBox);
return app;
}
The value returned by e.parameter.oneTextBox in the handler function is a string, in your example it should be "$120.00," and what you want is a numeric value... what I'd suggest is to use a replace() to remove all non numeric characters and convert that to a number like this :
var oneTextBoxNumValue = Number(e.parameter.oneTextBox.replace(/[^0-9]/g,''));// the regex ^0-9 takes everything not between 0 and 9 (and replace by '')
Using the same process on other textBoxes you can do everything you want with math operations after this conversion.
To get the results in $, simply add a '$' to your result
getElementById('oneTextBox').setText(resultNumeric+"$")
the only tricky thing is the decimal point, you'll need to take this into account in your conversion : $120.00, will become 12000 in numeric value so don't forget to divide the result somewhere or your stuff will become very expensive ! ;-)
Also I've had some rounding errors sometimes but it's always possible to handle quite easily, for example in a similar case I had to use something like this to get the correct result : (2.00 instead of 1.99 if quant = 2 in the example below, note that I divide the integer by 100 to get value with 2 decimals)
var total = parseInt(Number(quant)*valtotal*100+0.01)/100;
Hoping it will give some ideas to start with.
EDIT : here is a small code to illustrate :
function calcTest() {
var app = UiApp.createApplication().setTitle('TextField Calculator');
var button = app.createButton('Calculate');
var handler = app.createServerHandler('calc');
button.addClickHandler(handler);
var grid = app.createGrid(5, 2);
grid.setText(0, 0, 'value1 ');
grid.setWidget(0, 1, app.createTextBox().setName('value1').setText('$ 45.00/unit'));
grid.setText(1, 0, 'value2');
grid.setWidget(1, 1, app.createTextBox().setName('value2').setText('3 units'));
grid.setText(2, 0, 'press button to calculate');
grid.setWidget(2, 1, button);
grid.setText(3, 0, 'value3 = value1*1.35');
grid.setWidget(3, 1, app.createTextBox().setId('value3').setEnabled(false));
grid.setText(4, 0,'sum value1 + value2 + value3');
grid.setWidget(4, 1, app.createTextBox().setId('sum').setEnabled(false));
handler.addCallbackElement(grid);
app.add(grid);
var ss = SpreadsheetApp.getActive();
ss.show(app);
}
function calc(e){
var app = UiApp.getActiveApplication();
var value1 = Number(e.parameter.value1.replace(/[^0-9]/g,''))/100;
var value2 = Number(e.parameter.value2.replace(/[^0-9]/g,''));
var calcvalue = parseInt(value1*1.35*100)/100
var sumcalc = calcvalue+value1+value2
app.getElementById('value3').setText('$ '+calcvalue)
app.getElementById('sum').setText(sumcalc+' without unit;)')
return app
}
EDIT 2 : here is another code, a function that I use in an application to convert string values to Euros, it is slightly different in its approach but works pretty well.
function toEuro(val){
if(val==''){temp='';return temp}
var temp = val.toString().replace(/[^\d\.-]/g,'').split('.');
if(temp[0]==''){temp[0]='0'}
if(temp.length==1){var result = temp[0]+',00 €'}
else{
var int = temp[0]
var dec = temp[1]
if(dec.length==1){var result=int+','+dec+'0 €'}else{var result=int+','+dec+' €'}
}
return result
}
I am adding a users input in to UI as they add numbers and returning the results. The input is currency so I need to carry it out two decimals and not round.
Here is an example of my code:
function ceiling2(number) {
var ceiling2;
return ceiling2 = Math.ceil(number*100)/100;
}
//Totals
function lD23Total (e){
var app = UiApp.getActiveApplication();
var tB1v = parseInt(e.parameter.TextBox1);
var tB9v = parseInt(e.parameter.TextBox9);
var tB17v = parseInt(e.parameter.TextBox17);
var tB25v = parseInt(e.parameter.TextBox25);
var tB33v = parseInt(e.parameter.TextBox33);
var tB41v = parseInt(e.parameter.TextBox41);
var tB49v = parseInt(e.parameter.TextBox49);
var lD23 = app.getElementById("LabelD23").setStyleAttribute('fontWeight','bold');
var lD23T = tB1v + tB9v + tB17v + tB25v + tB33v + tB41v + tB49v;
lD23.setText("$ " + ceiling2(lD23T));
var app = UiApp.getActiveApplication();
app.close();
return app;
}
Currently it returns a rounded number.
I appreciate an suggestions you may offer!
Jon
The function parseInt() will convert the value to an integer, dropping the values after the decimal. Use parseFloat() instead.
I think your function is just fine...
if you remove the parseInt() and replace it either with parseFloat()as suggested by Eric or by Number() it should work...
if not then the problem might come from the way numbers are written:
If you used 26,4567 but you should use 26.4567 with a dot as separator in place of a comma.
Could you try and keep us informed ?
regards,
Serge
Or you can use this before sending to your function:
var newnumber=Number(number.toString().replace(",","."));// convert to string, replace comma with dot and set as number again.
and your function will work in both cases
I'm not so good with JS and for some reason when I try to add two fields together it joins them rather than adding the sum together.. this is the code I'm trying to use..
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = postageVal.substr(1); //68.50
var subtotal = subtotalVal.substr(1); //378.00
var totalVal = postage+subtotal;
alert(postage);
alert(subtotal);
alert(totalVal);
};
The totalVal is echoing/alerting out 68.50378.00 rather than adding them together.. could someone please tell me where I've gone wrong? :( The idea is to update the "total" textfield with totalVal, but I haven't gotten that far yet!
You need to convert your values to a float before adding them:
var totalVal = parseFloat(postage) + parseFloat(subtotal);
EDIT: Here's a complete example that includes a check for NaN:
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = parseFloat(postageVal.substr(1)); //68.50
var subtotal = parseFloat(subtotalVal.substr(1)); //378.00
var postageAsFloat = isNaN(postage) ? 0.0 : postage;
var subtotalAsFloat = isNaN(subtotal) ? 0.0 : subtotal;
var totalVal = postageAsFloat + subtotalAsFloat;
alert(postage);
alert(subtotal);
alert(totalVal);
};
Try converting the numbers to floats:
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = parseFloat(postageVal.substr(1)); //68.50
var subtotal = parseFloat(subtotalVal.substr(1)); //378.00
var totalVal = postage+subtotal;
alert(postage);
alert(subtotal);
alert(totalVal);
};
Everyone else has the right idea with parseFloat.
I just wanted to mention that I prefer to clean up numeric values like this (as opposed to parsing with substr):
var postageVal = document.getElementById('postage').value; //$68.50
var postage = parseFloat(postageVal.replace(/[^0-9.]/g, ''));
That replace call will remove any characters from the string except 0-9 and . (period). Not the /g at the end of the regex. That's important because, without it, only the first matching occurrence will be replaced.
parseFloat does the trick.
var postage = parseFloat(postageVal.substr(1));
var subtotal = parseFloat(subtotalVal.substr(1));
It's treating postage and subtotal as strings and concatenating them. You could try something like this:
var totalVal = 0+postage+subtotal;
That should force it into number mode.
However this could lead to problems if the values do not end up being numbers. You should run it through the proper number parsing functions and add checks to make sure they parsed correctly or else you will end up with NaN.
You need to parse the number first. This should work.
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = parseFloat( postageVal.substr(1) ); //68.50
var subtotal = parseFloat( subtotalVal.substr(1) ); //378.00
var totalVal = postage+subtotal;
alert(postage);
alert(subtotal);
alert(totalVal);
};
Unary plus should work:
var totalVal = (+postage) + (+subtotal);
But you probably intended your postage and subtotal variables to be numbers rather than strings, so...
var postage = +postageVal.substr(1); //68.50
var subtotal = +subtotalVal.substr(1); //378.00
var totalVal = postage+subtotal;
I haven't tested your code so there may be other issues but the fix below using parseFloat should stop the concatenation and add the numbers together.
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = postageVal.substr(1); //68.50
var subtotal = subtotalVal.substr(1); //378.00
var totalVal = parseFloat(postage)+parseFloat(subtotal);
alert(postage);
alert(subtotal);
alert(totalVal);
};
Having had the same sort of trouble I examined the JS parseFloat and parseInt functions and found them to be badly developed.
So therefore I prevent the whole problem by multiplying the element's value's * 1 before adding them. This forces JS to treat the result as numeric even if the value's were empty, so that it can be properly handled. As follows:
var TEMP = (1 * el_1.value) + (1 * el_2.value);
document.getElementById("el_tot").value = TEMP;
Assuming you see that "el_1" et al are the fieldnames in the form.
Thanks for all the answers! I'll try them out, I'm sure they're better than my solution:
<script type="text/javascript">
function calculateTotal() {
var postageVal = document.cart.postage.value;
var subtotalVal = document.cart.subtotal.value;
var postage = postageVal.substr(1);
var subtotal = subtotalVal.substr(1);
var totalVal = Number(postage)+Number(subtotal);
document.cart.total.value = "$"+totalVal.toFixed(2);
};
</script>
1.simple javascript addition program
<!DOCTYPE html>
<html>
<body>
<p>This calculation perfoms an addition, and returns the result by using a JavaScript. Check for a demo</p>
<form>
Enter no 1:<input type="text" name="a"><br>
Enter no 2:<input type="text" name="b"><br>
& nbsp;
<button onclick="calc(this.form)">Calculate</button>
</form>
<script>
function calc(form)
{
var a=eval(form.a.value);
var b=eval(form.b.value);
var c=a+b;
alert("The sum is " + c);
}
</script>
</body>
</html>