0

I'm dealing with ExtJS 6.2.1. I have a numberfield and need to limit it to three digits after a separator. So I use a decimalPrecision property:

{ xtype: 'numberfield', decimalPrecision: 3 }

Now, it seems that by default ExtJS uses midpoint rounding to the closest even number: 1.2345 turns into 1.234 and 1.2355 turns into 1.236. I need to change this behaviour to round away from zero, so that 1.2345 turns into 1.235. How can I achive this? Thanks.

1 Answers1

0

This action takes place in the private fixPrecision method.

        return parseFloat(Ext.Number.toFixed(parseFloat(value), precision));

I think the reason that it doesn't round as you expect, is that it's actually stored as a number slightly less than 1.2345 and it rounds down. This is due to the ways of storing floating-point numbers in RAM

To fix the component’s work, I suggest using the following override

Ext.define('Ext.form.field.NumberOverride', {
    override: 'Ext.form.field.Number',
    fixPrecision: function (value) {
        var me = this,
            nan = isNaN(value),
            precision = me.decimalPrecision;
        if (nan || !value) {
            return nan ? '' : value;
        } else if (!me.allowDecimals || precision <= 0) {
            precision = 0;
        }
        return (Math.round(value * (10 ** precision)) / (10 ** precision)).toFixed(precision);
    }
});

Fiddle

P.S. This thread helped me

pvlt
  • 1,843
  • 1
  • 10
  • 19
  • Thank you for answer. Haven't tried it, but it seems legit. I resolved my problem by setting decimalPrecision: 4 and adding a listener like that: listeners: { 'change': function(field, newValue, oldValue) { newValue = Math.round(newValue * 1000) / 1000; field.setValue(newValue); } } – Илья Иваницкий Apr 02 '20 at 12:24