alisabzevari
alisabzevari

Reputation: 8146

The most appropriate way to format numbers in angularjs

My problem is that I want to format numbers based on my language. For example, showing 123456.12345 in en-US as 123,456.12 or in fa-IR as ۱۲۳٬۴۵۶٫۱۲.

The best solution I can imagine is writing an angular filter but I think it is very slow because I need to show too many numbers in the view.

My question: Is there any better way to handle this problem or I have to use angular filters?

Upvotes: 3

Views: 475

Answers (1)

michelem
michelem

Reputation: 14590

Solution 1 with filters:

You can include the relative locale script in index.html as stated here:

<html ng-app>
 <head>
….
   <script src="angular.js"></script>
   <script src="i18n/angular-locale_de-de.js"></script>
….
 </head>
</html>

Then using the built-in filter number you can format them easily

Solution 2 with toLocaleString:

If you don't want to use filter, you have to convert the numbers "manually" using toLocaleString for each number you have:

$scope.myNumber = 9999.99;

$scope.myNumber.toLocaleString('de-DE');

This is a JSFidlle showing you how a number is formatted for de-DE locale instead the en-US one used by default

Upvotes: 1

Related Questions