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

2

5

What are the differences between:

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

Does one offer advantages over the other? Thanks

Deviltry answered 13/6, 2016 at 17:32 Comment(1)
Hi Sam, If either answer below helps you, could you click the tick button next to it. If not, you can add a comment on your question as to why not. DewdElectrophorus
C
10

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.

Chlorophyll answered 13/6, 2016 at 17:44 Comment(0)
S
4

The angular number filter does not change the original value of the property, for example:

{{ 3.14159 | number : 2 }} // this will give you 3.14 in the dom but the actual value will still be 3.14159

When you use a filter it is for display purposes only and does not change the property it just masks it. When you use toFixed() you are returning a string of the original number that is set to the specified decimal place which can then be set to another variable.

Shelton answered 13/6, 2016 at 17:38 Comment(3)
I suspect the number filter keeps the number as a number (although angular docs website is down right now, so I can't check). toFixed() casts the number to a string.Electrophorus
This is true, but my answer still stands true as well. angular filters are masks not setters.Shelton
Yes, filters are masks. It's worth mentioning though, that .toFixed() doesn't change the original number either. It returns a string which can be assigned to a variable.Electrophorus

© 2022 - 2024 — McMap. All rights reserved.