How to convert numbers into words in Angular

Front-end is easier than ever before if you get your hands dirty with Angular. If you are not familiar with Angular, it is a front-end framework based on TypeScript.

I have personally worked on several projects using the Angular framework. My experience with Angular and Spring Boot as a back-end is something I move forward with, in the days to come on my way as a full-stack developer.

Sometimes, we have to convert numbers into their equivalent word form. To achieve this, it is an easy task if you are using Angular for your front-end.

In this post, I am going to share how one can convert numbers into words in Angular.

There are several ways to achieve this. Here, I am going to share the easiest one.

Convert numbers into words in Angular

to-words Package

to-words package is an open-source package. It converts Numbers (including decimal points) into words. It also converts the numbers into words for currency.

If you are interested to read its official documentation, click here.

Installation

npm install to-words --save

Usage

Here is how you can import the package to your project after installation.

You can either import like this:

const { ToWords } = require('to-words');

OR

import { ToWords } from 'to-words';

Once you have imported it, you can instantiate an object of the class and use it to convert numbers in words as shown below:

const toWords = new ToWords();

let words = toWords.convert(123);
// words = One Hundred Twenty Three

words = toWords.convert(123.45);
// words = One Hundred Twenty Three Point Fourty Five

words = toWords.convert(123.045);
// words = One Hundred Twenty Three Point Zero Four Five

There are several options that you can opt for based on your requirements. For example, if you want the words to be American format, you can tweak the ToWords object as shown below.

const toWords = new ToWords({
  localeCode: 'en-US',
});

For more options, refer the official documentation.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *