Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Max Williams http://www.maximile.net/

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Javascript: convert integer to word (e.g. 18 -> "eighteen")

// 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;
}

Objective-C and Cocoa: Human-readable file size from number of bytes

// Returns a human-readable string showing the file size from the number of bytes

- (NSString *)stringFromFileSize:(int)theSize
{
	float floatSize = theSize;
	if (theSize<1023)
		return([NSString stringWithFormat:@"%i bytes",theSize]);
	floatSize = floatSize / 1024;
	if (floatSize<1023)
		return([NSString stringWithFormat:@"%1.1f KB",floatSize]);
	floatSize = floatSize / 1024;
	if (floatSize<1023)
		return([NSString stringWithFormat:@"%1.1f MB",floatSize]);
	floatSize = floatSize / 1024;

	// Add as many as you like

	return([NSString stringWithFormat:@"%1.1f GB",floatSize]);
}
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS