How to achieve midpoint rounding away from zero in numberfield in ExtJS?

137 Views Asked by At

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

There are 1 best solutions below

1
On BEST ANSWER

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