What's the difference between using toFixed and the angular number filter?

SamS picture SamS · Jun 13, 2016 · Viewed 15.6k times · Source

What are the differences between:

{{ 3.14159 | number : 2 }} and {{ 3.14159.toFixed(2) }}

Does one offer advantages over the other? Thanks

Answer

Ivan Barayev picture Ivan Barayev · Jun 13, 2016

Here is value still same but masked to 3.14

{{ 3.14159 | number : 2 }} 

but here

{{ 3.14159.toFixed(2) }}

toFixed(x) function is convert a number into a string, keeping only two decimals. for example

var num = 5.56789;
var n = num.toFixed();
// the output is = 6

if you use

var num = 5.56789;
var n = num.toFixed(2);
// the output is = 5.57

Note: if the desired number of decimals are higher than the actual number, nulls are added to create the desired decimal length.