DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Step-by-Step Guide: Application Using NestJs and Angular
  • When Angular APIs Return 200 but the Frontend Is Already Failing Users
  • Why Angular Performance Problems Are Often Backend Problems
  • Angular RxJS Unleashed: Supercharge Your App With Reactive Operators

Trending

  • Migrate a Hardcoded LangGraph Agent to LaunchDarkly AI Configs in 20 Minutes
  • Stop Debugging Glue Jobs Manually: Building an Agentic Observability Layer for Data Pipelines
  • Observability for Agents and Workflows: Tracing Prompts, Tool Calls, and Business Outcomes End-to-End
  • When One MVP Is Really Four Systems: A Better Way to Plan Multi-Role Apps
  1. DZone
  2. Coding
  3. JavaScript
  4. How to Get Localized Number Format Based on Country Using Angular 8

How to Get Localized Number Format Based on Country Using Angular 8

By 
Siddharth Gajbhiye user avatar
Siddharth Gajbhiye
·
Jan. 20, 20 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
11.4K Views

Join the DZone community and get the full member experience.

Join For Free

I have seen many users get confused about how different countries use different formats to display number format according to their country code. Most of the countries use "dot notation" as their separator, and many of the them use a "comma" as their separator. In this article, you will learn how to use a localized number format based on the country code and symbol to display using JavaScript's tolocalestring() method, which returns a string.

To explain the concept of localization and number format based on their locale, I am using my previous article as a reference to display the price based on different countries and their currencies.

So, please check my previous article, How to Create Nested Grid using Angular 8. As a reference, I am fetching the price and displaying it with the currency symbol based on their country and currency code. Additionally, in the nested grid, I am displaying all prices with a currency symbol.

In this article, I am just trying to explain the concept of tolocalestring(), which I am going to apply to the prices we're looking at. In my previous article, I just displayed price in "en" format, which is just a decimal number, but what if we want to see the price according to the respective country?

Backend

To fetch all countries, you just have to add the following code in SQL Server:

SQL
 




x
20


 
1
USE [Product]  
2
GO  
3
  
4
SET ANSI_NULLS ON  
5
GO  
6
  
7
SET QUOTED_IDENTIFIER ON  
8
GO  
9
  
10
CREATE TABLE [dbo].[Country](  
11
[CountryId] [int] NOT NULL,  
12
[CountryName] [nvarchar](50) NULL,  
13
[CountryCode] [nvarchar](50) NULL,  
14
[CurrencySymbol] [nvarchar](50) NULL,  
15
CONSTRAINT [PK_Country] PRIMARY KEY CLUSTERED  
16
(  
17
[CountryId] ASC  
18
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
19
) ON [PRIMARY]  
20
GO



After creating the table, it's time to insert records in the country table. For that, I  have inserted the code, so just copy and paste in SQL Server.

SQL
 




xxxxxxxxxx
1
16


 
1
INSERT [dbo].[Country] ([CountryId], [CountryName], [CountryCode], [CurrencySymbol]) VALUES (1, N'India', N'en-IN', N'INR')  
2
GO  
3
INSERT [dbo].[Country] ([CountryId], [CountryName], [CountryCode], [CurrencySymbol]) VALUES (2, N'Sweden', N'sv-SE', N'SEK')  
4
GO  
5
INSERT [dbo].[Country] ([CountryId], [CountryName], [CountryCode], [CurrencySymbol]) VALUES (3, N'England', N'en-GB', N'GBP')  
6
GO  
7
INSERT [dbo].[Country] ([CountryId], [CountryName], [CountryCode], [CurrencySymbol]) VALUES (4, N'Ireland', N'en-IE', N'EUR')  
8
GO  
9
INSERT [dbo].[Country] ([CountryId], [CountryName], [CountryCode], [CurrencySymbol]) VALUES (5, N'China', N'zh-CN', N'CNY')  
10
GO  
11
INSERT [dbo].[Country] ([CountryId], [CountryName], [CountryCode], [CurrencySymbol]) VALUES (6, N'Japan', N'ja-JP', N'JPY')  
12
GO  
13
INSERT [dbo].[Country] ([CountryId], [CountryName], [CountryCode], [CurrencySymbol]) VALUES (7, N'USA', N'en-US', N'USD')  
14
GO  
15
INSERT [dbo].[Country] ([CountryId], [CountryName], [CountryCode], [CurrencySymbol]) VALUES (8, N'Kuwait', N'ar-KW', N'KWD')  
16
GO  



In my previous article, I unfortunately forgot to give database records for product table so I am sharing that with you.

SQL
 




xxxxxxxxxx
1
16


 
1
INSERT [dbo].[Product] ([ProductId], [ProductCountryInformationId], [ArtNo], [Provider], [ProviderArtNo], [Brand]) VALUES (1, 1, N'100', N'OppoProvider', N'1Yu', N'Oppo')  
2
GO  
3
INSERT [dbo].[Product] ([ProductId], [ProductCountryInformationId], [ArtNo], [Provider], [ProviderArtNo], [Brand]) VALUES (2, 2, N'101', N'VivoProvider', N'2Yu', N'Vivo')  
4
GO  
5
INSERT [dbo].[Product] ([ProductId], [ProductCountryInformationId], [ArtNo], [Provider], [ProviderArtNo], [Brand]) VALUES (3, 3, N'102', N'SamsungProvider', N'3Yu', N'Samsung')  
6
GO  
7
INSERT [dbo].[Product] ([ProductId], [ProductCountryInformationId], [ArtNo], [Provider], [ProviderArtNo], [Brand]) VALUES (4, 4, N'103', N'NokiaProvider', N'4Yu', N'Nokia')  
8
GO  
9
INSERT [dbo].[Product] ([ProductId], [ProductCountryInformationId], [ArtNo], [Provider], [ProviderArtNo], [Brand]) VALUES (5, 5, N'104', N'SonyProvider', N'5Yu', N'Sony')  
10
GO  
11
INSERT [dbo].[Product] ([ProductId], [ProductCountryInformationId], [ArtNo], [Provider], [ProviderArtNo], [Brand]) VALUES (6, 6, N'105', N'HuaweiProvider', N'6Yu', N'Huawei')  
12
GO  
13
INSERT [dbo].[Product] ([ProductId], [ProductCountryInformationId], [ArtNo], [Provider], [ProviderArtNo], [Brand]) VALUES (7, 7, N'106', N'MotorolaProvider', N'7Yu', N'Motorola')  
14
GO  
15
INSERT [dbo].[Product] ([ProductId], [ProductCountryInformationId], [ArtNo], [Provider], [ProviderArtNo], [Brand]) VALUES (8, 8, N'107', N'HTCProvider', N'8Yu', N'HTC')  
16
GO  



For Product Country Information, which is our nested grid, below is the insert query that I, unfortunately, forgot to share it in my last article.

SQL
 




xxxxxxxxxx
1
32


 
1
INSERT [dbo].[ProductCountryInformation] ([ProductCountryInformationId], [Price], [BuyAccount], [SalesAccount], [CountryName], [ProductId]) VALUES (1, CAST(4010.23 AS Decimal(18, 2)), N'123', N'321', N'India', 1)  
2
GO  
3
INSERT [dbo].[ProductCountryInformation] ([ProductCountryInformationId], [Price], [BuyAccount], [SalesAccount], [CountryName], [ProductId]) VALUES (2, CAST(5623.32 AS Decimal(18, 2)), N'352', N'652', N'Sweden', 1)  
4
GO  
5
INSERT [dbo].[ProductCountryInformation] ([ProductCountryInformationId], [Price], [BuyAccount], [SalesAccount], [CountryName], [ProductId]) VALUES (3, CAST(6231.56 AS Decimal(18, 2)), N'557', N'889', N'England', 1)  
6
GO  
7
INSERT [dbo].[ProductCountryInformation] ([ProductCountryInformationId], [Price], [BuyAccount], [SalesAccount], [CountryName], [ProductId]) VALUES (4, CAST(9685.23 AS Decimal(18, 2)), N'665', N'652', N'Ireland', 1)  
8
GO  
9
INSERT [dbo].[ProductCountryInformation] ([ProductCountryInformationId], [Price], [BuyAccount], [SalesAccount], [CountryName], [ProductId]) VALUES (5, CAST(1253.01 AS Decimal(18, 2)), N'32', N'62', N'China', 1)  
10
GO  
11
INSERT [dbo].[ProductCountryInformation] ([ProductCountryInformationId], [Price], [BuyAccount], [SalesAccount], [CountryName], [ProductId]) VALUES (6, CAST(6325.89 AS Decimal(18, 2)), N'21', N'23', N'Japan', 1)  
12
GO  
13
INSERT [dbo].[ProductCountryInformation] ([ProductCountryInformationId], [Price], [BuyAccount], [SalesAccount], [CountryName], [ProductId]) VALUES (7, CAST(5212.56 AS Decimal(18, 2)), N'233', N'214', N'USA', 1)  
14
GO  
15
INSERT [dbo].[ProductCountryInformation] ([ProductCountryInformationId], [Price], [BuyAccount], [SalesAccount], [CountryName], [ProductId]) VALUES (8, CAST(4151.66 AS Decimal(18, 2)), N'452', N'452', N'Kuwait', 1)  
16
GO  
17
INSERT [dbo].[ProductCountryInformation] ([ProductCountryInformationId], [Price], [BuyAccount], [SalesAccount], [CountryName], [ProductId]) VALUES (9, CAST(1000.00 AS Decimal(18, 2)), N'5', N'6', N'India', 2)  
18
GO  
19
INSERT [dbo].[ProductCountryInformation] ([ProductCountryInformationId], [Price], [BuyAccount], [SalesAccount], [CountryName], [ProductId]) VALUES (10, CAST(2000.00 AS Decimal(18, 2)), N'4', N'5', N'Sweden', 2)  
20
GO  
21
INSERT [dbo].[ProductCountryInformation] ([ProductCountryInformationId], [Price], [BuyAccount], [SalesAccount], [CountryName], [ProductId]) VALUES (11, CAST(3000.00 AS Decimal(18, 2)), N'5', N'5', N'England', 2)  
22
GO  
23
INSERT [dbo].[ProductCountryInformation] ([ProductCountryInformationId], [Price], [BuyAccount], [SalesAccount], [CountryName], [ProductId]) VALUES (12, CAST(4000.00 AS Decimal(18, 2)), N'7', N'8', N'Ireland', 2)  
24
GO  
25
INSERT [dbo].[ProductCountryInformation] ([ProductCountryInformationId], [Price], [BuyAccount], [SalesAccount], [CountryName], [ProductId]) VALUES (13, CAST(5000.00 AS Decimal(18, 2)), N'8', N'8', N'China', 2)  
26
GO  
27
INSERT [dbo].[ProductCountryInformation] ([ProductCountryInformationId], [Price], [BuyAccount], [SalesAccount], [CountryName], [ProductId]) VALUES (14, CAST(6000.00 AS Decimal(18, 2)), N'8', N'9', N'Japan', 2)  
28
GO  
29
INSERT [dbo].[ProductCountryInformation] ([ProductCountryInformationId], [Price], [BuyAccount], [SalesAccount], [CountryName], [ProductId]) VALUES (15, CAST(7000.00 AS Decimal(18, 2)), N'8', N'7', N'USA', 2)  
30
GO  
31
INSERT [dbo].[ProductCountryInformation] ([ProductCountryInformationId], [Price], [BuyAccount], [SalesAccount], [CountryName], [ProductId]) VALUES (16, CAST(8000.00 AS Decimal(18, 2)), N'5', N'4', N'Kuwait', 2)  
32
GO  



Web API

Copy and paste the following code into your controller. This code will fetch all the countries that are in your database's Countries table.

C#
 




xxxxxxxxxx
1


 
1
[HttpGet]  
2
[Route("getAllCountry")]  
3
public object getAllCountry()  
4
{  
5
return DB.Countries.ToList();  
6
}  



If you don't have the complete code, I am sharing it with you below.

Complete Code for country controller:

C#
 




xxxxxxxxxx
1
34


 
1
using System.Linq;  
2
using System.Web.Http;  
3
using CompanyDetails.Models;  
4
namespace CompanyDetails.Controllers  
5
{  
6
    [RoutePrefix("api/Company")]  
7
    public class CompanyController : ApiController  
8
    {  
9
        CompanyEntities2 DB = new CompanyEntities2();  
10
     
11
        [HttpGet]  
12
        [Route("getAllCountry")]  
13
        public object getAllCountry()  
14
        {  
15
            return DB.Countries.ToList();  
16
        }  
17
  
18
        [HttpGet]  
19
        [Route("getAllProducts")]  
20
        public object getAllProducts(string countrycode)  
21
        {  
22
            var productDetails = DB.USP_GetAllProducts().ToList();  
23
            return productDetails;  
24
        }  
25
  
26
        [HttpGet]  
27
        [Route("getProductCountryInformation")]  
28
        public object getProductCountryInformation(int ProductId)  
29
        {  
30
            var prod = DB.USP_getCountryInfo(ProductId).ToList();           
31
            return prod;  
32
        }  
33
    }  
34
}



Frontend

This following code will fetch all the countries and bind it to our drop-down.

JavaScript
 




xxxxxxxxxx
1


 
1
public getCountry(){  
2
this._productService.getAllCountry().subscribe((data: any) => {  
3
this.country =data;  
4
console.log(data);  
5
});  
6
}  



This HTML code adds one drop-down which will bind all the countries which we are getting from database table country. Here, one method I have declared is onCountryChange, which fires when we change the drop-down selection.

Copy the following code and paste it in the product.component.html file inside the div that has the class, col-12 col-md-12.

HTML
 




xxxxxxxxxx
1


 
1
<select style="width: 160px;margin: 10px;" [(ngModel)]="countryId" (ngModelChange)="onCountryChange($event)"  
2
class="form-control" id="ddlCountry" name="ddlCountry" placeholder="Select a Country">  
3
<option [ngValue]="0" selected>--Choose Country--  
4
</option>  
5
<option [ngValue]="countryList.CountryId" *ngFor="let countryList of country">{{countryList.CountryName}}  
6
</option>  
7
</select>  



Copy the following code and paste it or replace it with ngOnInIt(), which will get all the countries and bind them to our drop-down.

JavaScript
 




xxxxxxxxxx
1


 
1
this.getCountry();  
2
this.countryId=0;  
3
this.getProducts(this.countryId);  
4
 



Copy the following code and paste it inside our service to fetch all the countries.

JavaScript
 




xxxxxxxxxx
1


 
1
getAllCountry(){  
2
this.url = 'http://localhost:49661/api/Company/getAllCountry';  
3
return this.http.get<any[]>(this.url);  
4
}  



Next, copy this code and paste it inside the getProducts method, which will convert the price based on their country and display it in our browser.

JavaScript
 




xxxxxxxxxx
1


 
1
for(var a =0;a<res.length;a++){  
2
res[a].Price =res[a].Price.toLocaleString(this.country[a].CountryCode, { style: 'currency', currency: this.country[a].CurrencySymbol });  
3
} 


 

 Then, paste the following code inside the showProductCountryInfo method.

JavaScript
 




xxxxxxxxxx
1


 
1
for (let i = 0; i < data.length; i++) {    
2
//Price Format based on country    
3
this.priceToDisplay[i] = data[i].Price;    
4
}


    

This method is used to check if any country is selected or not; if no country is selected, then price will display normally without any currency symbol and currency format. On the other hand, if a country is selected, then the price will display according to their country code and currency symbol.

JavaScript
 




x


 
1
toLocaleString(this.countryCode, { style: 'currency', currency: this.currencySymbol });



tolacalestring() is the JavaScript inbuilt method to convert a number to a string, which has some overloaded features, including country code and currency code (inside style curly braces), which we are fetching from the Countries table. 

This particular code is the method for changing the country. If $event is 0, no country is selected, and price will display normally. But, if the country code is present, then it will display the number according to their country currency code list.

JavaScript
 




xxxxxxxxxx
1
15


 
1
onCountryChange($event) {  
2
   debugger;  
3
   this.countryId = $event;  
4
   if($event==0){  
5
     for(var a =0;a<this.products.length;a++){  
6
       this.priceToDisplay[a] =this.products[a].Price;  
7
     }  
8
   }else{  
9
     this.countryCode =this.country[$event-1].CountryCode;  
10
     this.currencySymbol =this.country[$event-1].CurrencySymbol;  
11
       for(var a =0;a<this.products.length;a++){  
12
         this.priceToDisplay[a] =this.products[a].Price.toLocaleString(this.countryCode, { style: 'currency', currency:  this.currencySymbol });  
13
       }  
14
   }  
15
 }  



To avoid any confusion, I am sharing the full code, so just replace that with the old code if you already have it from my previous article.

products.components.ts  

JavaScript
 




xxxxxxxxxx
1
75


 
1
import { Component, OnInit } from '@angular/core';  
2
import { ProductsService } from './products.service';  
3
  
4
@Component({  
5
  selector: 'app-products',  
6
  templateUrl: './products.component.html',  
7
  styleUrls: ['./products.component.css']  
8
})  
9
export class ProductsComponent implements OnInit {  
10
  
11
  products = [];  
12
  countryCode: any;  
13
  currencySymbol:any;  
14
  productCountryInformation: any = [];  
15
  hideme = [];  
16
  Index: any;  
17
  countryId: any;  
18
  country: any;  
19
  priceToDisplay=[];  
20
  
21
   constructor(private _productService: ProductsService) {  
22
  }  
23
  ngOnInit() {  
24
    this.getCountry();  
25
    this.countryId=0;  
26
    this.getProducts(this.countryId);  
27
  }  
28
  
29
  public getCountry(){  
30
    this._productService.getAllCountry().subscribe((data: any) => {  
31
      this.country =data;  
32
      console.log(data);  
33
    });  
34
  }  
35
  
36
  public getProducts(countryId) {  
37
    let data = [];  
38
    this._productService.getAllProducts(countryId).subscribe((data: any) => {  
39
  
40
       for (let i = 0; i < data.length; i++) {  
41
        //Price Format based on country  
42
        this.priceToDisplay[i] = data[i].Price;  
43
      }  
44
      this.products =data;  
45
    })  
46
  
47
  }  
48
  public showProductCountryInfo(index,productId) {  
49
    this._productService.countryInfo(productId).subscribe((res:any)=>{  
50
  
51
      for(var a =0;a<res.length;a++){  
52
        res[a].Price =res[a].Price.toLocaleString(this.country[a].CountryCode, { style: 'currency', currency:  this.country[a].CurrencySymbol });  
53
      }  
54
    
55
      this.productCountryInformation[index] = res;  
56
    })  
57
    this.hideme[index] = !this.hideme[index];  
58
    this.Index = index;  
59
  }  
60
  onCountryChange($event) {  
61
    debugger;  
62
    this.countryId = $event;  
63
    if($event==0){  
64
      for(var a =0;a<this.products.length;a++){  
65
        this.priceToDisplay[a] =this.products[a].Price;  
66
      }  
67
    }else{  
68
      this.countryCode =this.country[$event-1].CountryCode;  
69
      this.currencySymbol =this.country[$event-1].CurrencySymbol;  
70
        for(var a =0;a<this.products.length;a++){  
71
          this.priceToDisplay[a] =this.products[a].Price.toLocaleString(this.countryCode, { style: 'currency', currency:  this.currencySymbol });  
72
        }  
73
    }  
74
  }  
75
}  



Also, I am sharing the complete source code so that it will be very easy to find the concerned output. Once you download the source code, then you just have to open it in VS Code and type npm install --save in the terminal. This will create a node_module file, and your project will run without any error. 

The following image is shown when you click on the plus icon to see the nested grid, which displays the price with all formats with their country name and currency symbol. 

For example, India uses dot notation for their decimal symbol with the rupee currency symbol.

 The following image is displayed when there is no country selected in the drop-down.

The following image is displayed when Sweden is selected in the drop-down.

The following image is displayed when Kuwait is selected in the drop-down.

The below image is the Countries table.


Further Reading

  • Login With Facebook and Google Using Angular 8.
  • How to Pack Angular 8 Applications on Regular War Files.
  • Angular: Everything You Need to Know [Tutorials].
AngularJS Database JavaScript

Opinions expressed by DZone contributors are their own.

Related

  • Step-by-Step Guide: Application Using NestJs and Angular
  • When Angular APIs Return 200 but the Frontend Is Already Failing Users
  • Why Angular Performance Problems Are Often Backend Problems
  • Angular RxJS Unleashed: Supercharge Your App With Reactive Operators

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook