Reputation: 91
I need to round a text field to 2 decimals. Here is the code with alert messages I set up. My concern is when I add a third number or more then the problem occurs. An example would be 100 + 10.11 = 110.11,(result = ) then 110.11 + 10.11 = 120.22 However, when I add a third number 120.22 + 10.11 it equals 130.32999999999998 and I want it to equal 130.33 What goes crazy in the third number added is the 'result' field equals 130.32999999999998
tbar: [{
text: 'Add',
tooltip:'Add the line item',
handler : function(){
var r = new iLineItemRec({
i_line_item_name: '',
i_line_item_amt: ''
});
iLineItemGrid.stopEditing();
iLineItemStore.insert(0, r);
iLineItemGrid.startEditing(0, 0);
Ext.getCmp('mike').setDisabled(false);
},
//Should this be scope:this or scope:iLineItemGrid?
scope:this
},
{
text: 'Delete',
tooltip:'Remove the selected line item',
handler: function(){
iLineItemGrid.stopEditing();
var r = iLineItemGrid.getSelectionModel().getSelectedCell();
iLineItemStore.removeAt(r[0]);
},
//Should this be scope:this or scope:iLineItemGrid?
scope:this
},
{
xtype: 'tbfill'
},
{
id: 'mike',
text: 'Submit',
tooltip:'Submit the line item',
//new
//disabled: true,
handler: function(){
iLineItemGrid.stopEditing();
// Will this code save changes to the database?
//iLineItemGrid.getStore().commitChanges();
iLineItemStore.commitChanges();
var iAmountTotalForLineItems = 0;
var iAmountInDueField = Ext.getCmp('iAmountDue').value;
var tempTotal = 0;
var result = 0;
iLineItemStore.each(function(addAmount){
iAmountTotalForLineItems += addAmount.get('i_line_item_amt');
});
alert('1 iAmountInDueField: ' + iAmountInDueField +' iLineItemTotalHold: '+iLineItemTotalHold + ' iAmountTotalForLineItems: '+ iAmountTotalForLineItems);
if (iLineItemTotalHold > iAmountTotalForLineItems ){
alert ('if');
tempTotal = iLineItemTotalHold - iAmountTotalForLineItems;
result = iAmountInDueField - tempTotal;
alert('two: '+result+' = '+iAmountInDueField+' - '+tempTotal );
}
else if (iLineItemTotalHold < iAmountTotalForLineItems ){
alert ('if2');
tempTotal = iAmountTotalForLineItems - iLineItemTotalHold;
result = iAmountInDueField + tempTotal;
alert('3: '+result+' = '+iAmountInDueField+' + '+tempTotal );
}
iLineItemTotalHold = iAmountTotalForLineItems;
Ext.getCmp('iAmountDue').setValue(result);
this.setDisabled(true);
}
//scope:this
}
]
var iLineItemTotalHold = 0;
Upvotes: 1
Views: 696
Reputation: 6090
You might find the toFixed()
method useful.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toFixed
From that page:
var n = 12345.6789;
n.toFixed(); // Returns "12346": note rounding, no fractional part
n.toFixed(1); // Returns "12345.7": note rounding
n.toFixed(6); // Returns "12345.678900": note added zeros
see also Formatting a number with exactly two decimals in JavaScript .
Upvotes: 1