使用 toFixed 和 angular 数字过滤器有什么区别?
What's the difference between using toFixed and the angular number filter?
有什么区别:
{{ 3.14159 | 2号 }}
和
{{ 3.14159.toFixed(2) }}
其中一个比另一个有优势吗?
谢谢
angular数字过滤器不改变属性的原始值,例如:
{{ 3.14159 | number : 2 }} // this will give you 3.14 in the dom but the actual value will still be 3.14159
当您使用过滤器时,它仅用于显示目的,不会更改 属性 它只是将其屏蔽。当您使用 toFixed()
时,您返回的是原始数字的字符串,该字符串设置为指定的小数位,然后可以将其设置为另一个变量。
这里的值仍然相同,但被屏蔽为 3.14
{{ 3.14159 | number : 2 }}
但是这里
{{ 3.14159.toFixed(2) }}
toFixed(x)
功能是将数字转换为字符串,只保留两位小数。例如
var num = 5.56789;
var n = num.toFixed();
// the output is = 6
如果你使用
var num = 5.56789;
var n = num.toFixed(2);
// the output is = 5.57
注意:如果所需的小数位数高于实际位数,则会添加空值以创建所需的小数长度。
有什么区别:
{{ 3.14159 | 2号 }} 和 {{ 3.14159.toFixed(2) }}
其中一个比另一个有优势吗? 谢谢
angular数字过滤器不改变属性的原始值,例如:
{{ 3.14159 | number : 2 }} // this will give you 3.14 in the dom but the actual value will still be 3.14159
当您使用过滤器时,它仅用于显示目的,不会更改 属性 它只是将其屏蔽。当您使用 toFixed()
时,您返回的是原始数字的字符串,该字符串设置为指定的小数位,然后可以将其设置为另一个变量。
这里的值仍然相同,但被屏蔽为 3.14
{{ 3.14159 | number : 2 }}
但是这里
{{ 3.14159.toFixed(2) }}
toFixed(x)
功能是将数字转换为字符串,只保留两位小数。例如
var num = 5.56789;
var n = num.toFixed();
// the output is = 6
如果你使用
var num = 5.56789;
var n = num.toFixed(2);
// the output is = 5.57
注意:如果所需的小数位数高于实际位数,则会添加空值以创建所需的小数长度。