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

后端 未结 7 2393
梦谈多话
梦谈多话 2020-12-14 10:39

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 sho

7条回答
  •  旧巷少年郎
    2020-12-14 10:58

    The popular solution didn't work for me. In fact the code in the solution is an exact duplicate of the EXT JS 3.3 source code which, for me, displays "1" instead of "1.00" when decimalPrecision is 2. Based on the popular solution's suggestion to override setValue, this is what I did:

    Ext.override(Ext.form.NumberField, {
        setValue: function(v) {
            var dp = this.decimalPrecision;
            if (dp < 0 || !this.allowDecimals) {
                dp = 0;
            }
            v = this.fixPrecision(v);
            v = Ext.isNumber(v) ? v : parseFloat(String(v).replace(this.decimalSeparator, "."));
            v = isNaN(v) ? '' : String(v.toFixed(dp)).replace(".", this.decimalSeparator);
            return Ext.form.NumberField.superclass.setValue.call(this, v);
        }
    });
    

    Even though the fixPrecision code seems to format the number with the desired precision, javascript would lose the precision during the manipulation it does on the two lines before the call to the superclass's setValue function. Setting the precision with toFixed when it is finally converted to a String made it work.

    Good luck!

提交回复
热议问题