EXTJS 번호 필드에서 소수점을 특정 정밀도로 표시하는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/1287584

  •  18-09-2019
  •  | 
  •  

문제

나는 a NumberField 그것은 유형의 값을 얻습니다 float JSON에서. 값이 정수 인 경우 소수점 이하 자리가 표시되지 않습니다. 항상 소수점 이하 2 곳을 보여주고 싶습니다. 이에 대한 구성 옵션이 있습니까?

내 선언은 다음과 같습니다.

items: [
    { 
        fieldLabel: 'Net Sales',
        name: 'netSales',
        allowBlank:false,
        decimalPrecision:2
    },
도움이 되었습니까?

해결책

어느 하나 연장하다 :

var myNumberField = Ext.extend(Ext.form.NumberField, {
        setValue : function(v){
            v = typeof v == 'number' ? v : String(v).replace(this.decimalSeparator, ".");
            v = isNaN(v) ? '' : String(v).replace(".", this.decimalSeparator);
            //  if you want to ensure that the values being set on the field is also forced to the required number of decimal places.
            // (not extensively tested)
            // v = isNaN(v) ? '' : this.fixPrecision(String(v).replace(".", this.decimalSeparator));
            return Ext.form.NumberField.superclass.setValue.call(this, v);
        },
        fixPrecision : function(value){
            var nan = isNaN(value);
            if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
               return nan ? '' : value;
            }
            return parseFloat(value).toFixed(this.decimalPrecision);
        }
    });

...
...

items: [new myNumberField({
        id  : 'net',
        fieldLabel: 'Net Sales',
        allowBlank:false,
        decimalPrecision:2
    }),

또는 우세하다, 그리고 그것은 응용 프로그램의 모든 숫자 필드에 영향을 미칩니다.

Ext.override(Ext.form.NumberField, {
    setValue : function(v){
            v = typeof v == 'number' ? v : String(v).replace(this.decimalSeparator, ".");
        v = isNaN(v) ? '' : String(v).replace(".", this.decimalSeparator);
        return Ext.form.NumberField.superclass.setValue.call(this, v);
    },
    fixPrecision : function(value){
        var nan = isNaN(value);
        if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
           return nan ? '' : value;
        }
        return parseFloat(value).toFixed(this.decimalPrecision);
    }
})

items: [{
        xtype   : 'numberfield',
        fieldLabel: 'Net Sales',
        allowBlank:false,
        decimalPrecision:2
    },

편집하다

첫 번째 setValue 메소드의 주석 섹션에 주목하십시오.

다른 팁

이것이 숫자 필드에서 소수를 강제하는 검색 쿼리의 최고 결과 였기 때문에 Extjs 4+를 사용하는 사람들을 위해 이것을 업데이트 할 것이라고 생각했습니다.

입력 필터링 Extjs 4이 Valuetoraw 함수로 위임되었으므로 사용 된 SetValue 기능은 실제로 ext.form.field.text에서 가져 오므로 아래에서 우선하는 것입니다.

또한 숫자 필드 당 옵션 ( 'ForcePrecision')을 옵션으로 표시하기로 결정했습니다. 즉, 재정의가 다음과 같이 보일 것입니다.

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;
    }
});

이것을 양식으로 사용하려면 다음과 같이 인스턴스화합니다.

{
  xtype: 'numberfield',
  name:  'decimalsfield',
  forcePrecision: true,     #defaults to false
  decimalPrecision: 3       #defaults to 2
}

분야가 인스턴스화되지 않았습니다 ForcePrecision : True 기본값과 똑같이 행동합니다.

인기있는 솔루션은 저에게 효과가 없었습니다. 실제로 솔루션의 코드는 Ext JS 3.3 소스 코드의 정확한 복제품으로, DecimalPrecision이 2 일 때 "1.00"대신 "1"을 표시하는 소스 코드입니다. 나는했다 :

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);
    }
});

FixPrecision 코드가 원하는 정밀도로 숫자를 형식화하는 것처럼 보이지만 JavaScript는 수퍼 클래스의 setValue 함수로 호출되기 전에 두 줄에서 수행하는 조작 중에 정밀도를 잃게됩니다. 마침내 문자열로 변환 될 때 두트 픽스로 정밀도를 설정하면 작동합니다.

행운을 빕니다!

가장 좋은 방법은 아마도 블러 이벤트에 리스너를 추가 한 다음 내장 된 JavaScript .Tofixed (2) 필드 값에 사용하는 것입니다.

옵션 DecimalPrecision 정의는 다음과 같습니다. "소수 분리기 후 표시되는 최대 정밀도 (기본값은 2)"입니다.

형식을 강요 할 수있는 옵션은 없으며, 아마도 Numberfield 클래스를 무시해야 할 것입니다.

아래와 같은 것을 원한다면 :

50을 입력하십시오> u는 50을 얻었습니다

50.10 > 50.10

50.123 > 50.12

이 시도:

, setValue: function (v) {
      if ( !v || isNaN(v)) {
        v = '';
      }
      else if (v % 1 != 0) {    //means number is not whole number
        v = this.fixPrecision(String(v).replace(".", this.decimalSeparator));
      }

     return Ext.form.NumberField.superclass.setValue.call(this, v);
}
, fixPrecision: function (value) {
    if (!this.allowDecimals || this.decimalPrecision == -1) {
       return value;
    }

    return parseFloat(value).toFixed(this.decimalPrecision);
}

이 코드는 저에게 훌륭합니다. EXTJS 4.2.0에서 "Valuetorow"재정의와 함께 작동하지 않습니다.

var myNumberField = Ext.extend(Ext.form.NumberField, {
    setValue : function(v){
        v = typeof v == 'number' ? v : String(v).replace(this.decimalSeparator, ".");
        v = isNaN(v) ? '' : String(v).replace(".", this.decimalSeparator);
        return Ext.form.NumberField.superclass.setValue.call(this, v);
    },
    fixPrecision : function(value){
        var nan = isNaN(value);
        if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
        return nan ? '' : value;
        }
        var val = parseFloat(value).toFixed(this.decimalPrecision);
        return val;
    },
    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, '.'));
        value = isNaN(value) ? '' : String(value).replace('.', decimalSeparator);
        return me.fixPrecision(value);
    }
});

...
...
items: [new myNumberField({
        id  : 'net',
        fieldLabel: 'Net Sales',
        allowBlank:false,
        decimalPrecision:2
    })

참조: ext.form.field.number에서 후행 0을 유지하는 방법?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top