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
},
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.