How do I force the display of a decimal in an ExtJS NumberField to a certain precision?

Mike Sickler picture Mike Sickler · Aug 17, 2009 · Viewed 45k times · Source

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

Answer

Dave A picture Dave A · Dec 6, 2012

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.