【问题标题】:Display a number with 2 decimal places in a number input在数字输入中显示带 2 位小数的数字
【发布时间】:2020-06-19 08:18:59
【问题描述】:

我有一个从 min: 0 到 max: 1 的输入。默认值为 1。但是我需要它显示为 1.00。我该怎么做?

输入html:

<input id="scale"
       name="scale"
       class="ui-g-9"
       type="number"
       [min]="0"
       [step]="0.01"
       [max]="1"
       [required]="true"
       [(ngModel)]="product.scale" <!-- this default value is 1.00 -->
       placeholder="Enter the scale">

【问题讨论】:

  • @JayantJeetTomar 不,这不是重复的,这个问题是关于 Angular js 的。当有默认值时,该解决方案也不起作用。只有当我去 -1 到 0.99 然后 +1 到 1.00 时它才有效
  • 只需将[(ngModel)]="product.scale" 更改为[(ngModel)]="parseFloat(product.scale).toFixed(2)"
  • @JayantJeetTomar 类型的 product.scale 是数字。 parseFloat 不适用于数字。
  • 更好。使用[(ngModel)]="(product.scale).toFixed(2)"

标签: html angular


【解决方案1】:

通过在组件中使用@ViewChild 来获取对输入元素的引用来修复它:

export class Component implements AfterViewChecked {
    @ViewChild('scale') scaleInput;

    /**
     * Angular after view checked handler
     */
    ngAfterViewChecked(): boolean {
        // Display the default value: 1 with 2 decimal places: 1.00
        this.scaleInput.nativeElement.value = parseFloat(this.scaleInput.nativeElement.value).toFixed(2);

        return super.ngAfterViewChecked();
    }
}

html 输入现在在哪里:

            <input #scale <!-- IMPORTANT PART -->
                   id="scale"
                   name="scale"
                   class="ui-g-9"
                   type="number"
                   (input)="setTo2FractionalDigits($event)"
                   [min]="0"
                   [step]="0.01"
                   [max]="1"
                   [required]="true"
                   [(ngModel)]="ivcProduct.scale"
                   placeholder="Enter the scale">

【讨论】:

    【解决方案2】:

    第 1 步:编辑您的输入标签

    <input id="scale"
           name="scale"
           class="ui-g-9"
           type="number"
           onchange="setTwoNumberDecimal"
           [min]="0"
           [step]="0.01"
           [max]="1"
           [required]="true"
           [(ngModel)]="(product.scale).toFixed(2)" <!-- this default value is 1.00 -->
           placeholder="Enter the scale">
    

    第 2 步:编写 setTwoDecimalPlace 方法

    function setTwoNumberDecimal(event) {
        this.value = parseFloat(this.value).toFixed(2);
    }
    

    【讨论】:

    • 不起作用。我收到错误:Parser Error: Unexpected token '=' at column 30 in [(ivcProduct.scale).toFixed(2)=$event] in ng:///IvcModule/IvcProductDialogComponent.html@35:19 ("roup&gt; &lt;app-control-group fieldName="contact" label="Scale" labelClass="ui-g-3"&gt; [ERROR -&gt;]&lt;input #scale id="scale" name="scale" class="ui-g-9" "): ng:///IvcModule/IvcProductDialogComponent.html@26:12, Directive NgControlStatus
    猜你喜欢
    • 2010-11-21
    • 2014-05-03
    • 2013-01-29
    • 2018-02-14
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    • 2016-03-01
    相关资源
    最近更新 更多