作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
似乎无法解决这个问题。我尝试了许多不同的变化。这是在Angular项目上。
我希望即使用户只键入一个整数,百分数始终显示两位小数。
我无法切换数据类型,因为围绕它编写的许多其他代码都是数字。
问题是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'.
<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...
最佳答案
您已经完成了所有工作,但还没有将正确的内容放在一起。解析float,并且toFixed(2)
正确返回了一个2位小数的字符串,您只需要一起使用它们:parseFloat(input).toFixed(2)
关于angular - 将两个小数位添加到数字TypeScript Angular ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55184945/
我是一名优秀的程序员,十分优秀!