Return to Snippet

Revision: 15501
at July 7, 2009 21:39 by iloveitaly


Initial Code
function numberFormat(number, decimals, thousands_sep, decimal_sep) {
		//   var_number.number_format([decimals ,thousand separator,decimal separator]);
		//   var number: number to format
		//   decimals: how many decimal numbers (default value 0);
		//   thousand separator: char that define the thousandecimal_sep (default value ,);
		//   decimal separator: char the defines the decimals (default value .);
		
		if(isNaN(number)) return undefined;
		if(decimals < 0) return undefined;   
		if(decimals == undefined) decimals = 0;
		if(thousands_sep == undefined) thousands_sep = ',';
		if(decimal_sep == undefined) decimal_sep = '.';
		
		var returned = number.toString().split('.'), str_begin, str_after, temp_str = "", i;
		
		if(returned.length == 1) {
			str_begin = returned[0]
			str_after = '';
		} else if(returned.length == 2) {
			str_begin = returned[0];
			str_after = returned[1];
			str_after = str_after.substr(0, 2);
		} else {
			trace("uncaught number format");
		}
		
		// thousands seperator
		if(str_begin.length > 3) {
			for(i = 0; i < str_begin.length; i++) {
				if(((str_begin.length - i) % 3) == 0 && i != str_begin.length - 1) {
					temp_str = temp_str + thousands_sep + str_begin.charAt(i);
				} else {
					temp_str = temp_str + str_begin.charAt(i);
				}
			}
		} else {
			temp_str = str_begin;
		}
		
		//   ----------------------
		//   decimals
		//   if decimals==0 return
		//   ----------------------
		if(decimals > 0) {
			str_after = str_after.substr(0, decimals);
			
			if(str_after.length < decimals) {
				while(str_after.length < decimals) {
					str_after += '0';
				}
			}
		}
		
		if(decimals > 0) {
			return temp_str + decimal_sep + str_after;
		} else {
			return temp_str;
		}
	}

Initial URL

                                

Initial Description
This code was adapted from a snippet I found somewhere awhile back... can't claim complete credit

Initial Title
Format Number in ActionScript

Initial Tags
number, format, actionscript

Initial Language
ActionScript