Created
November 12, 2017 06:44
-
-
Save itsTeknas/97800c238937606df1250fa9ff52737a to your computer and use it in GitHub Desktop.
An Angular 4 pipe to convert a number to an equivalent words representation for Indian Rupees.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Pipe, PipeTransform } from '@angular/core'; | |
@Pipe({ | |
name: 'numberToWords' | |
}) | |
export class NumberToWordsPipe implements PipeTransform { | |
a = [ | |
'', | |
'one ', | |
'two ', | |
'three ', | |
'four ', | |
'five ', | |
'six ', | |
'seven ', | |
'eight ', | |
'nine ', | |
'ten ', | |
'eleven ', | |
'twelve ', | |
'thirteen ', | |
'fourteen ', | |
'fifteen ', | |
'sixteen ', | |
'seventeen ', | |
'eighteen ', | |
'nineteen ']; | |
b = [ | |
'', | |
'', | |
'twenty', | |
'thirty', | |
'forty', | |
'fifty', | |
'sixty', | |
'seventy', | |
'eighty', | |
'ninety']; | |
transform(value: any, args?: any): any { | |
if (value) { | |
let num: any = Number(value); | |
if (num) { | |
if ((num = num.toString()).length > 9) { return 'We are not the Iron Bank, you can lower down the stakes :)'; } | |
const n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/); | |
if (!n) {return ''; } | |
let str = ''; | |
str += (Number(n[1]) !== 0) ? (this.a[Number(n[1])] || this.b[n[1][0]] + ' ' + this.a[n[1][1]]) + 'crore ' : ''; | |
str += (Number(n[2]) !== 0) ? (this.a[Number(n[2])] || this.b[n[2][0]] + ' ' + this.a[n[2][1]]) + 'lakh ' : ''; | |
str += (Number(n[3]) !== 0) ? (this.a[Number(n[3])] || this.b[n[3][0]] + ' ' + this.a[n[3][1]]) + 'thousand ' : ''; | |
str += (Number(n[4]) !== 0) ? (this.a[Number(n[4])] || this.b[n[4][0]] + ' ' + this.a[n[4][1]]) + 'hundred ' : ''; | |
str += (Number(n[5]) !== 0) ? ((str !== '') ? 'and ' : '') + | |
(this.a[Number(n[5])] || this.b[n[5][0]] + ' ' + | |
this.a[n[5][1]]) + 'rupee' : ''; | |
return str; | |
} else { | |
return ''; | |
} | |
} else { | |
return ''; | |
} | |
} | |
} |
Thanks for the code !
Awesome, thank you so much
it is not working for real number.
it works well
what if I need to convert decimal values into words
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source Algorithm : https://stackoverflow.com/a/14767071/1942593