Home Blog Page 12

JavaScript – Currency Number Formatting using Intl.NumberFormat

0
Javascript - Number to Currency Fornat using Intl NumberFormat
Javascript - Number to Currency Fornat using Intl NumberFormat

Hi Guy’s Welcome to Proto Coders Point, In this article let’s check put how to convert number to currency format number in javascirpt using Intl.NumberFormat.

In the world web development, we make use of javascript, and if you are building any application where you want to want to format a number into a currency number format, specially when you want to show the number in a form of item price in currencies. To ensure consistent and user-friendly experience, software developers need to format numbers according to user’s locale & the currency he/she is preference. In javascript to convert normal number into currency number is simple and straightforward using `Intl.NumberFormat` object.

Video Tutorial

Currency Number Formatting using Intl.NumberFormat

Introduction to Intl.NumberFormat

The Intl.NumberFormat is a Internationalization API which comes with all the web browsers, using which software developers can format number according to their needs may be in locale or currency format, It has flexiable option to customize the number in terms of how the number is displayed to the end users.

The Code – Javascript number formating in currency format with currency symbol

const price = 10000000;

console.log(Intl.NumberFormat().format(price));

console.log("US -> ", Intl.NumberFormat('en-US').format(price));
console.log("IN -> ", Intl.NumberFormat('en-IN').format(price));

console.log("US with symbol -> ", Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD'
}).format(price));

console.log("IN with symbol -> ", Intl.NumberFormat('en-IN', {
    style: 'currency',
    currency: 'INR'
}).format(price));

Let’s break down above code in part for better understanding:

  1. Default Number formating: The first 2 line demonstrate the simple usage of ‘Intl.NumberFormat’. In log i have use it, it formats the price variable which is a number into currency number format using default locale.
  2. Locale-Specific Formating: The next 2 line is to demostrate how to format to number for specific locales. NumberFormat() i am passing locate code i.e en-US for United States and en-IN for India.
  3. Currency Number formating with Currency Symbol: The last 2 example code is to give styling for the number. The style property is set to 'currency', and the currency property is used to specify the currency symbol and code. The code formats price as US Dollars (USD) for the United States and Indian Rupees (INR) for India, including currency symbols.

Conclusion

In this article, we have explored how to use Intl.NumberFormat object in Javascript to format numbers into currency. Whether you or you company is build an e-commerce platform, financial application or any other application that requires currency number format to be displayed, Intl.NumberFormat() is your go-to solution to build user-friendly application.


Similar Article

Flutter display digits in currency format

Debouncing in flutter – A Effective way to implement search field

0
flutter debouncing
flutter debouncing

Hi Guys, Welcome to Proto Coders Point This flutter article is on what is debouncing & how to implement it in flutter.

What is Debouncing?

Debouncing is a effective way to implement searching functionality. Basically Debouncing is a technique by which we can control and manage user input by preventing unnecessary hits to server API.

When is debouncing used?

Debouncing is usually used in search fields, such as when a user type a letter in a textField, A API is called and then a fetched results from API is displayed.

Just consider that you are calling a API when there is a key pressed (user types a letters) onChanged method is used in Flutter TextField, Let’s assume that a user types a word dog in the search field, Here for each letter typed by user onChanged() method makes a call to API means 3 times API is called, which is not a right way to implement search field. This creates a rapid and unnecessary operation like network api call request or state updates. To prevent this we make use of Deboucing in flutter.

Debouncing was build to create a delay before performing request event for user input. There a a delay in user typing a letter, So when a user continuously types word “dog” and then keep a gap of 500 milliseconds, Now the API is triggered making it a more effective way to implement searching field in flutter.

How to implement debouncing in flutter?

Here are steps to implement debounce in flutter.

First let create a Timer() object will name it as _debounceTimer.

Timer? _debounceTimer;

Then in TextField we have a method onChanged() a listener that listens to each key/letter press or cleared by user in textField

TextField(
          controller: _controller,
          onChanged: (text) {
               print('Making API Call for Text: $text (${text.characters.length})');
          },
          decoration: InputDecoration(labelText: 'Enter text'),
        ),

In above code onChanged() method listens to each letter types in textField, That makes a call to a API on eack key press. To prevent this will make use of debouncing technique that is simple keeping a time gap before making a call to the server API.

TextField(
          controller: _controller,
          onChanged: (text) {
              if (_debounceTimer != null) {
                  _debounceTimer!.cancel();
              }

           _debounceTimer = Timer(Duration(milliseconds: 500), () {
                    // Perform your desired action here, e.g., make an API request.
                    print('Performing action with text: $value');
              });
          },
          decoration: InputDecoration(labelText: 'Enter text'),
  ),

In above example, Then a user types letters in textField rapidly the timer object reset itself so the API call is not made, and if the user keep a gap of 500 millisecond period within his typing speed then API call is made like searching a list of data that started with letter typed by user in textField.


Complete code – debouncing in flutter

import 'package:flutter/material.dart';
import 'dart:async';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DebounceExample(),
    );
  }
}

class DebounceExample extends StatefulWidget {
  @override
  _DebounceExampleState createState() => _DebounceExampleState();
}

class _DebounceExampleState extends State<DebounceExample> {
  final TextEditingController _controller = TextEditingController();
  Timer? _debounceTimer;

  @override
  void dispose() {
    _controller.dispose();
    _debounceTimer?.cancel();
    super.dispose();
  }

  void _onTextChanged(String value) {
    // Debounce the text input by delaying the action for 500 milliseconds.
    if (_debounceTimer != null) {
      _debounceTimer!.cancel();
    }

    _debounceTimer = Timer(Duration(milliseconds: 500), () {
      // Perform your desired action here, e.g., make an API request.
      print('Performing action with text: $value');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Debounce Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: TextField(
          controller: _controller,
          onChanged: _onTextChanged,
          decoration: InputDecoration(labelText: 'Enter text'),
        ),
      ),
    );
  }
}

Most Utilized API Protocal Architecture

0
Most Utilized API Protocal Architecture
Most Utilized API Protocal Architecture

Now a day in tech industry, Several API(Application Programming Interface) protocols and architectures are been widely used to build application. Keep in mind that this protocols has evolved more popularity since then. Her are some of the most utilized API protocols in industries right now.

1. MQTT (Message Queuing Telemetry Transport)


If an Lightweight & efficient messaging protocol that is specially built for low-bandwidth, high-latency or unreliable network. The MQTT protocol is originally developed by IBM in 1990’s and from that time to current time it is been widely used in Internet of Things(IoT) basically it is an publish-subscribe messaging protocol for efficient data exchange between devices using mqtt secure order.
( MQTT a best for option for IOT to application communication in real-time)

mqtt

2. GraphQL


This technology is an Query language that allows clients to request exactly the data that is needed, The GraphQL API’s is built that enables a client to request specific set of data and reduce fetching extra or under-fetching(means data getting lost can be handled here).
(Query Language for flexible data retrieval.)

graphql

3. SOAP (Simple Object Access Protocol)


SOAP is a protocol that is used in exchanging structured information for web services. In SOAP it use XML format for messages. SOAP can handle various lowe-level protocol which Include HTTP, SMTP and more.
(Web Service Protocol for structured data exchange)

SOAP

4. Webhook


A Webhook uses event or trigger based real-time data to another application. Webhook basically enable a way of communication between systems by allowing one system to provide data to another system. Webhook is simple words are HTTP callbacks that send real-time data to a specified URL when a specific event occurs.
( Event Notification Mechanism)

Webhook

5. REST (Representational State Transfer)


This Architecture is a designed networded application with is standardized HTTP methods(like GET, POST, PUT and DELETE). REST API’s usually used JSON format data to communicate.
( Web Service Architecture for stateless communication)

REST API

6. WebSocket


A WebSocket are Full-duplex communication protocol over a single TCP connection, allowing interactive and real-time data exchange.
( Real-time Communication Protocol.)

WebSocket

How to choose State Management for Flutter Project

0
state management for flutter

In Flutter, Choosing a right State management Library is Crucial for your flutter project and it future, In the sense choosing right State Management can be greate for your flutter project like maintainability, performance and development cost and the application speed.

The Choice of State Management Library/Dependencies depends on various factors like:

  • Project Size
  • Complexity
  • Time Frame
  • Team Size
  • Code Quality

Learn about different State Management

Below are few Dependencies or Library that support state management for flutter ecosystem.

1. setState: This is an in-Built and simple state management provided by flutter itself. This can be used when you are building small application which has limited user interaction and changes in states.

2. Provider: This is one of the popular package when it comes with state management, It uses the InheritedWidget mechanism to manage state efficiently. Flutter Provider is suitable when you are build medium-sized flutter application provides a balance between simplicity & flexibility.
straightforward solution for managing state without boilerplate codes.

3. BLoC: This stands for Business Logic Component (BLoC): The BLoC mainly focus on state management using stream and events. This Library is popular when you are building larger & more complex project. Should be used when developing flutter application that has lot of user interaction.

4. GetX: This package not only provide state management it also comes with varieties of utilities, like dependencies injection, getx state management, pop up, Internationalization, Route management, change theme and more. it’s well know for it’s simplicity as it is easily to understand and the app performance is also high using getx for state management.

5. Riverpod: This package is advanced provider package that offer a strong dependencies injection and state management capabilities. This is best to use when your flutter project require high and complex data management & scalability.

Please note that, There’s no one fit answer to choosing a state management for your flutter project. It all depend on the project complexity and your software developer who has great knowledge on state management.

NodeJS Script to upload file to Google Drive using GoogleAPI’s

0
Nodejs upload drive to google drive

Hi Guy’s Welcome to Proto Coders Point. This article is on how to upload files to Google Drive using NodeJS.

Uploading a file to google drive by using nodejs code take several steps, which include steps:

  • Creating Project in Google Cloud Console.
  • Enabling Google Drive API.
  • Creating Service Account Credentials.
  • Creating NodeJS Project and Install Necessary Libraries.
  • NodeJS Code to Upload File to Google Drive.

Step 1: Setup a Google Cloud Console Project:

  • Go to Google Cloud Console : https://console.cloud.google.com/.
  • Create a new Project or select an existing one.
  • Now Navigate to “API’s & Services” > “Library”.
  • In Search for “Google Drive API” and click on enable button for your project.
how to enable google drive api

Step 2: Create Service Account Credentials API

In google cloud console, Navigate to “API’s & Services” > “Credentials”.

Click on “Create Credentials” > Select “Service Account”.

Enter Service Account Name, Service account ID then click DONE.


Step 3: Creating API Key JSON File for authentication

Once Service Account is been created, click on Service Account Email as soon in above image.

Then Click on Keys > Add Key > Create New Key

service account api key json file

This will create a json file download it, It contain api key by making use of which you can write a nodeJS Script that can upload files into your google drive.


Step 4: Creating a Folder & Give Access

Now, Once Service Account email is created, We need to create a Folder on Google Drive that will have full access permission for the service account we created, Basically share that folder with Service Account we created in above step.

Click on 3 dot on the folder that you want to share with service account, then click on share and enter the email address of service account and done.


Step 5: Creating NodeJS Project

Create a folder & open a terminal in that folder path itself.

In Terminal/CMD enter npm init to make normal folder into nodeJS project


Step 6: Installing required Library/Module

To upload files into google drive from Nodejs script we need few library:

fs (File Sytem) -> To work with Files of System.

googleapis -> To communicate with google drive API.

Install those using below cmd:

npm install fs googleapis

Step 7: Finally NodeJS Script/Function to Upload file to Google Drive using Google Drive API

In your NodeJS Project, paste the credential .json file download from above step.

In my project I have created a javascript code by name app.js, what will have a function that will upload file to google drive.

app.js

const fs = require('fs');
const { google }= require('googleapis');

const apikeys = require('./apikeys.json');
const SCOPE = ['https://www.googleapis.com/auth/drive'];

// A Function that can provide access to google drive api
async function authorize(){
    const jwtClient = new google.auth.JWT(
        apikeys.client_email,
        null,
        apikeys.private_key,
        SCOPE
    );

    await jwtClient.authorize();

    return jwtClient;
}

// A Function that will upload the desired file to google drive folder
async function uploadFile(authClient){
    return new Promise((resolve,rejected)=>{
        const drive = google.drive({version:'v3',auth:authClient}); 

        var fileMetaData = {
            name:'mydrivetext.txt',    
            parents:['1bZoTbqCew34MGr1DfgczcA40ECM_QhKg'] // A folder ID to which file will get uploaded
        }

        drive.files.create({
            resource:fileMetaData,
            media:{
                body: fs.createReadStream('mydrivetext.txt'), // files that will get uploaded
                mimeType:'text/plain'
            },
            fields:'id'
        },function(error,file){
            if(error){
                return rejected(error)
            }
            resolve(file);
        })
    });
}

authorize().then(uploadFile).catch("error",console.error()); // function call

Now run the code

node app.js

Flutter Alphabetical Scroll List

0
Flutter Alphabetical Scroll List
Flutter Alphabetical Scroll List

Hi Guy’s Welcome to Proto Coders Point, In this Flutter Article let’s learn how to implement Alphabetical scroll list in flutter.

An Alphabetical Scroll List also known as A-Z Scroll List, is the most commonly used in mobile applications that help users to quickly navigate to any large set of list in an alphabetical order.

Here are some common places where an Aplhabetical Scroll List can be used:

  1. Contact List.
  2. Music & Video Playlist.
  3. Address Books.
  4. Product Lists.
  5. Country or City List.

An Alphabetical Scroll List is versatile UI element that ca be applied in many use case like contact list, music, video, address, country and many more for efficient navigation through the large dataset.

How to Implement alphabetical scroll list in flutter

In Flutter to create an alphabetical listview which can be scrollable using easily A-Z Alphabet, We will be using a dependency/library called azlistview that allow scrolling to a specific items in the list for easy navigation.

Video Tutorial

Install Library into flutter project

Open pubspec.yaml file and under dependencies section add:

dependencies:
  azlistview: ^2.0.0  #version may change in future

After adding the dependencies hit pub get button or enter “flutter pub get” in terminal to download the package into your flutter project as external packages.

Import to use it

import 'package:azlistview/azlistview.dart';

Source Code to Implement A-Z Scroll list in flutter

Flutter Alphabetical Scroll List

In “lib” directory of your flutter project, Create a Dart File by name “CountryList.dart”

CountryList.dart

This will be a class that extends ISuspensionBean which comes with azlistview package.

import 'package:azlistview/azlistview.dart';

class CountryList extends ISuspensionBean{

  final String title;
  final String tag;


  CountryList({required this.title, required this.tag});

  @override
  String getSuspensionTag() {
    // TODO: implement getSuspensionTag
    return tag;
  }

}

main.dart

In this page we will load the list of country name which can we easily alphabetically scrolled to navigate to particular items in the listview using A-Z.

import 'dart:typed_data';
import 'package:azlistview/azlistview.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ui/CountryList.dart';
void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // hide the debug banner
      debugShowCheckedModeBanner: false,
      title: 'ProtoCodersPoint.com',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: AlphabeticalListView(items: [
          "Afghanistan", "Albania","Algeria","Andorra","Angola","Anguilla","Antigua &amp; Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia &amp; Herzegovina","Botswana","Brazil","British Virgin Islands","Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Cape Verde","Cayman Islands","Chad","Chile","China","Colombia","Congo","Cook Islands","Costa Rica","Cote D Ivoire","Croatia","Cruise Ship","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Estonia","Ethiopia","Falkland Islands","Faroe Islands","Fiji","Finland","France","French Polynesia","French West Indies","Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guam","Guatemala","Guernsey","Guinea","Guinea Bissau","Guyana","Haiti","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Isle of Man","Israel","Italy","Jamaica","Japan","Jersey","Jordan","Kazakhstan","Kenya","Kuwait","Kyrgyz Republic","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macau","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Mauritania","Mauritius","Mexico","Moldova","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique","Namibia","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","Norway","Oman","Pakistan","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Saint Pierre &amp; Miquelon","Samoa","San Marino","Satellite","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","South Africa","South Korea","Spain","Sri Lanka","St Kitts &amp; Nevis","St Lucia","St Vincent","St. Lucia","Sudan","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor L'Este","Togo","Tonga","Trinidad &amp; Tobago","Tunisia","Turkey","Turkmenistan","Turks &amp; Caicos","Uganda","Ukraine","United Arab Emirates","United Kingdom","Uruguay","Uzbekistan","Venezuela","Vietnam","Virgin Islands (US)","Yemen","Zambia","Zimbabwe"
        ],),
      ),
    );
  }
}


class AlphabeticalListView extends StatefulWidget {
  final List<String> items;

  AlphabeticalListView({Key? key, required this.items}) : super(key: key);

  @override
  State<AlphabeticalListView> createState() => _AlphabeticalListViewState();
}

class _AlphabeticalListViewState extends State<AlphabeticalListView> {

  List<CountryList> items = [];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initList(widget.items);
  }

  void initList(List<String> items){
    this.items = items.map((item) => CountryList(title: item,tag: item[0])).toList();
  }


  @override
  Widget build(BuildContext context) {
    return AzListView(data: items, itemCount: items.length, itemBuilder: (context,index){
      final item = items[index];
      return Card(
        child: ListTile(
          title: Text(item.title),
        ),
      );
    });
  }
}