How to add and multiply text boxes together in google apps script? - javascript

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
}

Related

Calculating 2 values from fields but it's not working properly

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"));

Display floating point with starting values in DAT.GUI

I have a small menu made with dat.gui JavaScript library. I use different lines with some initial values which are displayed (these initial values are modified during the execution of code).
My issue is, for example, that instead of display a value "15", I would like to display "15.0000". I try to used toFixed(4) function but without success.
Here's the raw (without "toFixed(4)" function) code snippet :
var componentThetaInit = 15;
var componentPhiInit = 15;
var gui = new dat.GUI({
autoplace: false,
width: 350,
height: 9 * 32 - 1
});
var params = {
StartingVector : '',
ComponentVectorTheta : componentThetaInit,
ComponentVectorPhi : componentPhiInit
};
gui.add(params, 'StartingVector').name('Starting Vector :');
controllerComponentVectorTheta = gui.add(params, 'ComponentVectorTheta', minComponentTheta, maxComponentTheta, 0.0001).name('Component θ ');
controllerComponentVectorPhi = gui.add(params, 'ComponentVectorPhi', minComponentPhi, maxComponentPhi, 0.0001).name('Component φ ');
Now I tried :
var params = {
StartingVector : '',
ComponentVectorTheta : componentThetaInit.toFixed(4),
ComponentVectorPhi : componentPhiInit.toFixed(4)
};
but this doesn't work. Here's below a capture of what I get ("15" instead of "15.0000") before the execution :
Once the code is running, the 4 floating points are well displayed (because values are no more integers) : this is actually the initial values (before animation) that I would like to be displayed like "15.0000" instead of "15".
The result is the same by declaring :
var componentThetaInit = 15.0000;
var componentPhiInit = 15.0000;
I have also tried :
ComponentVectorTheta : parseFloat(componentThetaInit.toFixed(4)),
ComponentVectorPhi : parseFloat(componentPhiInit.toFixed(4))
If anyone could see what's wrong, this would be nice.
Thanks
First, some minor bugs. There were some missing variable declarations. I added:
var minComponentTheta = -10.0;
var maxComponentTheta = 100.0;
var minComponentPhi = -100.0;
var maxComponentPhi = 100.0;
2) The autoplace param (which should be autoPlace, capital P) has nothing to do with decimal places... it appears to be an option to automatically add the UI to the DOM.
None of this actually fixes the issue. It's a problem that starts with javascript. If you put this code in the console you'll see the same problem:
var a = 15.0000;
console.log(a);
// prints 15 and not 15.0000
When a number is an integer, it's an integer. To get around this, you can have your default value have a non integer value like 15.0001.
This probably isn't what you're looking for though. So, if you are up for modifying the code for dat.gui.js you can force it to set the value of the input to the string version of the number value. Find the code that looks like this and copy and paste the code below replacing it. I've simply added a toFixed at the end of the first line in the function. Be aware that when you get the value now, it will be a string and not a number, so to do math with it you'll want to parseFloat() on it before using it.
NumberControllerBox.prototype.updateDisplay = function updateDisplay() {
this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision).toFixed(this.__precision);
return _NumberController.prototype.updateDisplay.call(this);
};
In the unminified JS version, ^ that's on line 2050.
I verified this works as you want
Just leave it like this:
ComponentVectorTheta : componentThetaInit.toFixed(4),
ComponentVectorPhi : componentPhiInit.toFixed(4)
Consider this:
a = 15; // a is an integer now
b = a.toFixed(4); // b is the string "15.0000"
c = parseFloat(b); // c is a number (internally, probably an integer)
d = c.toString(2); // d is the string "1111"
e = parseInt(d, 2);// e is an integer again
assert(a === e); // true

When passing number with comma to text box why getElementById truncate the number after the comma

Please check this code :
function CalCPM()
{
var nv = document.getElementById('txtviews').value;
var nc = document.getElementById('txtcost').value;
var result =parseFloat(nc) / parseFloat(nv)/1000;
if(!isNaN(result))
{
document.getElementById('cpm').value = result.toFixed(4);
}
}
it work fine expect when you put comma in the number, means if you put in txtviews 1000000 and in txtcost 3000 you get a correct result that is 3.000
However if you use commas in any of the numbers then the problem starts, like
if you put in txtviews 1,000,000 and in txtcost 3,000
then the result will be 0.000003
OR if you start by putting value for txtcost first
then the result will be 3000.0000
which is not a correct value either way, any idea what is the problem??
I believe you'd have to strip them out, and then add them back in (the commas, that is)..
function CalCPM()
{
var nv = document.getElementById('txtviews').value.replace(',','');
var nc = document.getElementById('txtcost').value.replace(',','');
var result =parseFloat(nc) / parseFloat(nv)/1000;
if(!isNaN(result))
{
document.getElementById('cpm').value = Number(result).toLocaleString('en');
}
}
This can simply solve by using reg-ex :
function CalCPM()
{
var nv = (document.getElementById('txtviews').value).replace(/,/g,'');
var nc = (document.getElementById('txtcost').value).replace(/,/g,'');
var result =parseFloat(nc) / parseFloat(nv)/1000;
if(!isNaN(result))
{
document.getElementById('cpm').value = Number(result).toFixed(4);
}
}

Big-integer Fibonacci sequence diverges at 36'th term: Project Euler #25

So I am trying to solve project euler #25 via the big integer brute force method with this module. Everything seems to go properly until the 36'th term, which actually decreases. Then the terms increase as they should, and then decrease again; they never go over 10 million. I have also noticed the 36'th term has all digits correct except one as it is supposed to be 14930352 but I get 4930352 Could this be a problem with my code or a bug in the module?
var bigInt = require('big-integer');
var number = bigInt(1);
var last = bigInt(1);
for(i=0;i<50;i++){
number = number.add(last);
last = number.minus(last);
console.log(number.toString());
}
Looks like a bug in the library. If you use a tmp variable it works fine.
var bigInt = require('big-integer');
var number = bigInt(1);
var last = bigInt(1);
for(i=0;i<50;i++){
//number = number.add(last);
//last = number.minus(last);
var tmp = number.add(last);
last = number;
number = tmp;
console.log((i + 3) + ":" + number.toString());
}

Adding User input without rounding (Google Apps Script)

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

Categories

Resources