I have a form with a NumberField
that gets values of type float
from JSON. If the values happen to be whole numbers, then no decimal places are shown. I would like to show 2 decimal places at all times. Is there a config option for this?
Here's my declaration:
items: [
{
fieldLabel: 'Net Sales',
name: 'netSales',
allowBlank:false,
decimalPrecision:2
},
either extend :
var myNumberField = Ext.extend(Ext.form.NumberField, {
setValue : function(v){
v = typeof v == 'number' ? v : String(v).replace(this.decimalSeparator, ".");
v = isNaN(v) ? '' : String(v).replace(".", this.decimalSeparator);
// if you want to ensure that the values being set on the field is also forced to the required number of decimal places.
// (not extensively tested)
// v = isNaN(v) ? '' : this.fixPrecision(String(v).replace(".", this.decimalSeparator));
return Ext.form.NumberField.superclass.setValue.call(this, v);
},
fixPrecision : function(value){
var nan = isNaN(value);
if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
return nan ? '' : value;
}
return parseFloat(value).toFixed(this.decimalPrecision);
}
});
...
...
items: [new myNumberField({
id : 'net',
fieldLabel: 'Net Sales',
allowBlank:false,
decimalPrecision:2
}),
or override, and that will effect all numberfields in your application:
Ext.override(Ext.form.NumberField, {
setValue : function(v){
v = typeof v == 'number' ? v : String(v).replace(this.decimalSeparator, ".");
v = isNaN(v) ? '' : String(v).replace(".", this.decimalSeparator);
return Ext.form.NumberField.superclass.setValue.call(this, v);
},
fixPrecision : function(value){
var nan = isNaN(value);
if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
return nan ? '' : value;
}
return parseFloat(value).toFixed(this.decimalPrecision);
}
})
items: [{
xtype : 'numberfield',
fieldLabel: 'Net Sales',
allowBlank:false,
decimalPrecision:2
},
EDIT
Notice the commented section in the first setValue method.