As this was the top result for a search query about forcing decimals in a NumberField, thought I would update this for those using ExtJS 4+
The input filtering since ExtJS 4 has been delegated to a valueToRaw function, the setValue function used is actually from Ext.form.field.Text, so that's what I'm overriding below.
I also decided to have the forcing of displaying decimals to be an option ('forcePrecision') configurable per NumberField, which means the override will look like this:
Ext.override(Ext.form.NumberField, {
forcePrecision : false,
valueToRaw: function(value) {
var me = this,
decimalSeparator = me.decimalSeparator;
value = me.parseValue(value);
value = me.fixPrecision(value);
value = Ext.isNumber(value) ? value : parseFloat(String(value).replace(decimalSeparator, '.'));
if (isNaN(value))
{
value = '';
} else {
value = me.forcePrecision ? value.toFixed(me.decimalPrecision) : parseFloat(value);
value = String(value).replace(".", decimalSeparator);
}
return value;
}
});
To use this in your form, you'd instantiate it like this:
{
xtype: 'numberfield',
name: 'decimalsfield',
forcePrecision: true, #defaults to false
decimalPrecision: 3 #defaults to 2
}
Fields not instantiated with forcePrecision: true behave exactly like the default.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…