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
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone >

Javascript: Convert Integer To Word (e.g. 18 -> "eighteen")

Snippets Manager user avatar by
Snippets Manager
·
Mar. 20, 07 · · Code Snippet
Like (0)
Save
Tweet
2.76K Views

Join the DZone community and get the full member experience.

Join For Free
// Convert a positive integer less than 1000 to its word representation.


var units = new Array ("Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen");
var tens = new Array ("Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety");

function num(it) {
	var theword = "";
	var started;
	if (it>999) return "Lots";
	if (it==0) return units[0];
	for (var i = 9; i >= 1; i--){
		if (it>=i*100) {
			theword += units[i];
			started = 1;
			theword += " hundred";
			if (it!=i*100) theword += " and ";
			it -= i*100;
			i=0;
		}
	};
	
	for (var i = 9; i >= 2; i--){
		if (it>=i*10) {
			theword += (started?tens[i-2].toLowerCase():tens[i-2]);
			started = 1;
			if (it!=i*10) theword += "-";
			it -= i*10;
			i=0
		}
	};
	
	for (var i=1; i < 20; i++) {
		if (it==i) {
			theword += (started?units[i].toLowerCase():units[i]);
		}
	};
	return theword;
}
JavaScript Convert (command) Data Types

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 10 Books Every Senior Engineer Should Read
  • Why I'm Choosing Pulumi Over Terraform
  • How to Leverage Method Chaining To Add Smart Message Routing in Java
  • Debugging Deadlocks and Race Conditions

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo