Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What are the differences between:

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

Does one offer advantages over the other? Thanks

like image 455
SamS Avatar asked Jun 13 '16 17:06

SamS


People also ask

What is the toFixed () function used for?

Description. toFixed() returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.

Is toFixed a string?

In JavaScript, toFixed() is a Number method that is used to convert a number to fixed-point notation (rounding the result where necessary) and return its value as a string. Because toFixed() is a method of the Number object, it must be invoked through a particular instance of the Number class.

Does toFixed return string?

The method toFixed(n) rounds the number to n digits after the point and returns a string representation of the result.

What is number in angular?

isNumber() function in AngularJS is used to determine the parameter inside isNumber function is a number or not. It returns true if the reference is a number otherwise returns false. Syntax: angular.


2 Answers

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.

like image 190
Ivan Barayev Avatar answered Oct 05 '22 01:10

Ivan Barayev


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.

like image 25
Ohjay44 Avatar answered Oct 05 '22 01:10

Ohjay44