How To Get Localized Number Format Based On Country Using Angular 8

To explain the concept of localization and number format based on their locale I am taking 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 currency symbols based on their country and currency code, additionally, in a nested grid, I am displaying all price formats with currency symbols.

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

Introduction

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

BACK END

To fetch all countries you just have to add the below code in the SQL server.

USE [Product]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Country](
    [CountryId] [int] NOT NULL,
      NULL,
      NULL,
    [CurrencySymbol] [nvarchar](50) NULL,
    CONSTRAINT [PK_Country] PRIMARY KEY CLUSTERED 
    (
        [CountryId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

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

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

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

INSERT [dbo].[Product] ([ProductId], [ProductCountryInformationId], [ArtNo], [Provider], [ProviderArtNo], [Brand]) VALUES (1, 1, N'100', N'OppoProvider', N'1Yu', N'Oppo')
GO
INSERT [dbo].[Product] ([ProductId], [ProductCountryInformationId], [ArtNo], [Provider], [ProviderArtNo], [Brand]) VALUES (2, 2, N'101', N'VivoProvider', N'2Yu', N'Vivo')
GO
INSERT [dbo].[Product] ([ProductId], [ProductCountryInformationId], [ArtNo], [Provider], [ProviderArtNo], [Brand]) VALUES (3, 3, N'102', N'SamsungProvider', N'3Yu', N'Samsung')
GO
INSERT [dbo].[Product] ([ProductId], [ProductCountryInformationId], [ArtNo], [Provider], [ProviderArtNo], [Brand]) VALUES (4, 4, N'103', N'NokiaProvider', N'4Yu', N'Nokia')
GO
INSERT [dbo].[Product] ([ProductId], [ProductCountryInformationId], [ArtNo], [Provider], [ProviderArtNo], [Brand]) VALUES (5, 5, N'104', N'SonyProvider', N'5Yu', N'Sony')
GO
INSERT [dbo].[Product] ([ProductId], [ProductCountryInformationId], [ArtNo], [Provider], [ProviderArtNo], [Brand]) VALUES (6, 6, N'105', N'HuaweiProvider', N'6Yu', N'Huawei')
GO
INSERT [dbo].[Product] ([ProductId], [ProductCountryInformationId], [ArtNo], [Provider], [ProviderArtNo], [Brand]) VALUES (7, 7, N'106', N'MotorolaProvider', N'7Yu', N'Motorola')
GO
INSERT [dbo].[Product] ([ProductId], [ProductCountryInformationId], [ArtNo], [Provider], [ProviderArtNo], [Brand]) VALUES (8, 8, N'107', N'HTCProvider', N'8Yu', N'HTC')
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.

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)
GO
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)
GO
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)
GO
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)
GO
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)
GO
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)
GO
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)
GO
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)
GO
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)
GO
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)
GO
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)
GO
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)
GO
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)
GO
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)
GO
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)
GO
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)
GO

WEB API

In your controller just copy the below code and paste it. This code will fetch all the countries that are in your database table

[HttpGet]
[Route("getAllCountry")]
public object getAllCountry()
{
    return DB.Countries.ToList();
}

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

Complete Code for country controller.

using System.Linq;
using System.Web.Http;
using CompanyDetails.Models;

namespace CompanyDetails.Controllers
{
    [RoutePrefix("api/Company")]
    public class CompanyController : ApiController
    {
        CompanyEntities2 DB = new CompanyEntities2();

        [HttpGet]
        [Route("getAllCountry")]
        public object getAllCountry()
        {
            return DB.Countries.ToList();
        }

        [HttpGet]
        [Route("getAllProducts")]
        public object getAllProducts(string countrycode)
        {
            var productDetails = DB.USP_GetAllProducts().ToList();
            return productDetails;
        }

        [HttpGet]
        [Route("getProductCountryInformation")]
        public object getProductCountryInformation(int ProductId)
        {
            var prod = DB.USP_getCountryInfo(ProductId).ToList();
            return prod;
        }
    }
}

FRONT END

The below code will fetch all the countries and bind them to our dropdown.

public getCountry() {
  this._productService.getAllCountry().subscribe((data: any) => {
    this.country = data;
    console.log(data);
  });
}

This HTML code adds one dropdown that will bind all the countries that we are getting from the database table country.

Here one method I have declared is "onCountryChange" which fires when we change the dropdown selection.

Copy the below code and paste it into the product.component.html file inside this p tag which has classclass="col-12 col-md-12".

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

Copy the below code and paste it or replace it with ngOnInIt() which will get all the countries and bind them to our dropdown.

this.getCountry();
this.countryId = 0;
this.getProducts(this.countryId);

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

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

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

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

And paste the below code inside the showProductCountryInfo method.

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

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

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

tolacalestring() is the JavaScript inbuilt method to convert numbers into strings which has some overloaded features including country code and currency code (inside style curly braces) which we are fetching from the country table.

This particular code is the method for changing the country, if the $event is 0 means no country is selected then the price will display normally but if the country code is present then it will display the number according to their country currency code list which we are fetching from the database table country.

onCountryChange($event) {
    debugger;
    this.countryId = $event;
    if ($event == 0) {
        for (var a = 0; a < this.products.length; a++) {
            this.priceToDisplay[a] = this.products[a].Price;
        }
    } else {
        this.countryCode = this.country[$event - 1].CountryCode;
        this.currencySymbol = this.country[$event - 1].CurrencySymbol;
        for (var a = 0; a < this.products.length; a++) {
            this.priceToDisplay[a] = this.products[a].Price.toLocaleString(this.countryCode, { style: 'currency', currency: this.currencySymbol });
        }
    }
}

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

products.components.ts

import { Component, OnInit } from '@angular/core';
import { ProductsService } from './products.service';

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {

  products = [];
  countryCode: any;
  currencySymbol: any;
  productCountryInformation: any = [];
  hideme = [];
  Index: any;
  countryId: any;
  country: any;
  priceToDisplay = [];

  constructor(private _productService: ProductsService) {
  }

  ngOnInit() {
    this.getCountry();
    this.countryId = 0;
    this.getProducts(this.countryId);
  }

  public getCountry() {
    this._productService.getAllCountry().subscribe((data: any) => {
      this.country = data;
      console.log(data);
    });
  }

  public getProducts(countryId) {
    let data = [];
    this._productService.getAllProducts(countryId).subscribe((data: any) => {
      for (let i = 0; i < data.length; i++) {
        // Price Format based on country
        this.priceToDisplay[i] = data[i].Price;
      }
      this.products = data;
    })
  }

  public showProductCountryInfo(index, productId) {
    this._productService.countryInfo(productId).subscribe((res: any) => {
      for (var a = 0; a < res.length; a++) {
        res[a].Price = res[a].Price.toLocaleString(this.country[a].CountryCode, { style: 'currency', currency: this.country[a].CurrencySymbol });
      }
      this.productCountryInformation[index] = res;
    })
    this.hideme[index] = !this.hideme[index];
    this.Index = index;
  }

  onCountryChange($event) {
    debugger;
    this.countryId = $event;
    if ($event == 0) {
      for (var a = 0; a < this.products.length; a++) {
        this.priceToDisplay[a] = this.products[a].Price;
      }
    } else {
      this.countryCode = this.country[$event - 1].CountryCode;
      this.currencySymbol = this.country[$event - 1].CurrencySymbol;
      for (var a = 0; a < this.products.length; a++) {
        this.priceToDisplay[a] = this.products[a].Price.toLocaleString(this.countryCode, { style: 'currency', currency: this.currencySymbol });
      }
    }
  }
}

Also, I am sharing its 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 in the terminal "npm install --save" This will create a node_module file and your project will run without any error.

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

For ex: India uses dot notation for their decimal symbol and with the rupee currency symbol.

Sweden uses commas to display their symbol and so on.

Comma

The below image shows when there is no country selected in the dropdown.

Different Countries

The below image shows when Sweden is selected in the dropdown; then the price will display according to Sweden's country and currency code.

 Sweden

The below image shows when Kuwait is selected in the dropdown; then the price will display according to Kuwait country and currency code.

 Kuwait

The below image shows when the USA is selected in the dropdown; then the price will display according to the USA country and currency code.

 Currency code

Price displays when USA country is selected but its nested grid displays all country price formats.

USA country

The below image is a country table.

Country table

Conclusion

In this article, I tried to explain how you get localized number format based on the country.

I am just a learner and eager to learn new things not related to technology, but also in all aspects.

"Never stop learning, because life stops teaching".....by Gautam Buddha.

At last please don't forget to give your valuable feedback/comments/questions about this article. Please let me know if you liked and understood this article and how I could improve it.