Добавление двух знаков после запятой в число TypeScript Angular - PullRequest
1 голос
/ 15 марта 2019

Не могу понять это. Я перепробовал много разных вариантов. Это на угловом проекте.

Я хочу, чтобы процентное число всегда отображалось с двумя десятичными знаками, даже если пользователь вводит только целое число.

Я не могу переключить тип данных, так как много другого кода было написано вокруг него как число.

Проблема в том, что TypeScript не позволяет использовать var, и у меня возникают проблемы с добавлением дополнительных нулей или округления указанного числа до двух десятичных знаков. Кажется, их всегда раздевают.

Декларация:

 percent: number;

Некоторые вещи, которые я пробовал.

1:
this.percent = Math.round(this.percent * 1e2) / 1e2;

2:
this.percent = this.percent.toFixed(2); // Throws error cant assign string to num because to fixed returns string

3:
const percentString = this.percent.toString() + '.00';
this.percent = parseFloat(percentString) // Strips 00 (Tried this to just add zeros to whole number as test [will be making it more dynamic])

4:
this.percent = Math.round(this.percent * 100) / 100;

5: (This whole function from another SOF)

  addZeroes(num) {
// Convert input string to a number and store as a variable.
    let value = Number(num).toString();
// Split the input string into two arrays containing integers/decimals
    const res = num.split('.');
// If there is no decimal point or only one decimal place found.
    if (res.length === 1 || res[1].length < 3) {
// Set the number to two decimal places
      value = parseFloat(value).toFixed(2);
    }
// Return updated or original number.
    return value;
  }

and then

this.percent = parseFloat(this.addZeroes(this.percent));

6:
this.percent = parseFloat(this.percent).toFixed(2); // Error inside parseFloat: TS2345: Argument of type 'number' is not assignable to parameter of type 'string'

7:
this.percent = parseFloat(this.percent.toString()).toFixed(2); // Throws error on this.percent assignment: TS2322: Type 'string' is not assignable to type 'number'

8:
this.percent = Number(this.percent).toFixed(2); // Error on assignment: TS2322: Type 'string' is not assignable to type 'number'.

HTML:

  <mat-form-field>
    <input
      matInput
      [numbers]="'.'"
      type="text"
      maxlength="5"
      [placeholder]="'Percent'"
      [(ngModel)]="percent"
      (change)="updateDollarAmountNew()"
      numbers
      name="percent">
  </mat-form-field>

Я также пробовал прокладывать трубопроводы на передней части, но у меня тоже проблемы с этим.

[(ngModel)]="p.percent | number : '1.2-2'" // Error: ng: The pipe '' could not be found

[(ngModel)]="{{percent | number : '1.2-2'}}" // Error: unexpected token '}}'

[(ngModel)]={{percent | number : '1.2-2'}} // Error: Attribute number is not allowed here

[(ngModel)]={{percent | number : 2}} // Error: : expected

// And so on...

Спасибо за ваши советы и помощь!

Ответы [ 2 ]

3 голосов
/ 15 марта 2019

Правильный подход - трактовать его как число и форматировать в представлении.

Однако вы смешиваете переплет и форматирование, например: [(ngModel)]="{{percent | number : '1.2-2'}}" (очень грубо!) Эквивалентно высказываниюна английском: привязать мою модель к строковой интерполяции ... моя модель .

Попробуйте:

<div>{{percent | number : '1.2-2'}}</div>

Есть хорошие примеры использования числовых каналов вдокументы: https://angular.io/api/common/DecimalPipe#example

2 голосов
/ 15 марта 2019

Вы сделали всю работу, но просто не соединили нужные кусочки. Синтаксический анализ работает, и toFixed(2) правильно возвращал строку с двумя десятичными разрядами, вам просто нужно использовать их вместе:

parseFloat(input).toFixed(2)

...