格式化是通过格式操作使任意类型的数据转换成一个字符串。例如下面这样
<script><br />
console.log(chopper.format('{0} - {1} - {2}', 12, 24, 25)); // outputs "12 - 24 - 25"<br />
</script>
下面是一个完整的代码,可以复制到自己的项目中。
">http://code.jquery.com/jquery-1.9.1.min.js">>
<script><br />
(function() {<br />
var chopper = window.chopper = window.chopper || { cultures: {} },<br />
math = Math,<br />
formatRegExp = /\{(\d+)(:[^\}]+)?\}/g,<br />
FUNCTION = "function",<br />
STRING = "string",<br />
NUMBER = "number",<br />
OBJECT = "object",<br />
NULL = "null",<br />
BOOLEAN = "boolean",<br />
UNDEFINED = "undefined",<br />
slice = [].slice,<br />
globalize = window.Globalize,<br />
standardFormatRegExp = /^(n|c|p|e)(\d*)$/i,<br />
literalRegExp = /(<a href="file://\\.)|(['][^']*[']?)|(["][^"]*["]?)/g">\\.)|(['][^']*[']?)|(["][^"]*["]?)/g,<br />
commaRegExp = /\,/g,<br />
EMPTY = "",<br />
POINT = ".",<br />
COMMA = ",",<br />
SHARP = "#",<br />
ZERO = "0",<br />
PLACEHOLDER = "??",<br />
EN = "en-US",<br />
objectToString = {}.toString;<br />
//cultures<br />
chopper.cultures["en-US"] = {<br />
name: EN,<br />
numberFormat: {<br />
pattern: ["-n"],<br />
decimals: 2,<br />
",": ",",<br />
".": ".",<br />
groupSize: [3],<br />
percent: {<br />
pattern: ["-n %", "n %"],<br />
decimals: 2,<br />
",": ",",<br />
".": ".",<br />
groupSize: [3],<br />
symbol: "%"<br />
},<br />
currency: {<br />
pattern: ["($n)", "$n"],<br />
decimals: 2,<br />
",": ",",<br />
".": ".",<br />
groupSize: [3],<br />
symbol: "$"<br />
}<br />
},<br />
calendars: {<br />
standard: {<br />
days: {<br />
names: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],<br />
namesAbbr: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],<br />
namesShort: [ "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" ]<br />
},<br />
months: {<br />
names: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],<br />
namesAbbr: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]<br />
},<br />
AM: [ "AM", "am", "AM" ],<br />
PM: [ "PM", "pm", "PM" ],<br />
patterns: {<br />
d: "M/d/yyyy",<br />
D: "dddd, MMMM dd, yyyy",<br />
F: "dddd, MMMM dd, yyyy h:mm:ss tt",<br />
g: "M/d/yyyy h:mm tt",<br />
G: "M/d/yyyy h:mm:ss tt",<br />
m: "MMMM dd",<br />
M: "MMMM dd",<br />
s: "yyyy'-'MM'-'ddTHH':'mm':'ss",<br />
t: "h:mm tt",<br />
T: "h:mm:ss tt",<br />
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",<br />
y: "MMMM, yyyy",<br />
Y: "MMMM, yyyy"<br />
},<br />
"/": "/",<br />
":": ":",<br />
firstDay: 0,<br />
twoDigitYearMax: 2029<br />
}<br />
}<br />
};<br />
function findCulture(culture) {<br />
if (culture) {<br />
if (culture.numberFormat) {<br />
return culture;<br />
}<br />
if (typeof culture === STRING) {<br />
var cultures = chopper.cultures;<br />
return cultures[culture] || cultures[culture.split("-")[0]] || null;<br />
}<br />
return null;<br />
}<br />
return null;<br />
}<br />
function getCulture(culture) {<br />
if (culture) {<br />
culture = findCulture(culture);<br />
}<br />
return culture || chopper.cultures.current;<br />
}<br />
function expandNumberFormat(numberFormat) {<br />
numberFormat.groupSizes = numberFormat.groupSize;<br />
numberFormat.percent.groupSizes = numberFormat.percent.groupSize;<br />
numberFormat.currency.groupSizes = numberFormat.currency.groupSize;<br />
}<br />
chopper.culture = function(cultureName) {<br />
var cultures = chopper.cultures, culture;<br />
if (cultureName !== undefined) {<br />
culture = findCulture(cultureName) || cultures[EN];<br />
culture.calendar = culture.calendars.standard;<br />
cultures.current = culture;<br />
if (globalize && !globalize.load) {<br />
expandNumberFormat(culture.numberFormat);<br />
}<br />
} else {<br />
return cultures.current;<br />
}<br />
};<br />
chopper.culture(EN);<br />
//number formatting<br />
function formatNumber(number, format, culture) {<br />
culture = getCulture(culture);<br />
var numberFormat = culture.numberFormat,<br />
groupSize = numberFormat.groupSize[0],<br />
groupSeparator = numberFormat[COMMA],<br />
decimal = numberFormat[POINT],<br />
precision = numberFormat.decimals,<br />
pattern = numberFormat.pattern[0],<br />
literals = [],<br />
symbol,<br />
isCurrency, isPercent,<br />
customPrecision,<br />
formatAndPrecision,<br />
negative = number < 0,<br />
integer,<br />
fraction,<br />
integerLength,<br />
fractionLength,<br />
replacement = EMPTY,<br />
value = EMPTY,<br />
idx,<br />
length,<br />
ch,<br />
hasGroup,<br />
hasNegativeFormat,<br />
decimalIndex,<br />
sharpIndex,<br />
zeroIndex,<br />
hasZero, hasSharp,<br />
percentIndex,<br />
currencyIndex,<br />
startZeroIndex,<br />
start = -1,<br />
end;<br />
//return empty string if no number<br />
if (number === undefined) {<br />
return EMPTY;<br />
}<br />
if (!isFinite(number)) {<br />
return number;<br />
}<br />
//if no format then return number.toString() or number.toLocaleString() if culture.name is not defined<br />
if (!format) {<br />
return culture.name.length ? number.toLocaleString() : number.toString();<br />
}<br />
formatAndPrecision = standardFormatRegExp.exec(format);<br />
// standard formatting<br />
if (formatAndPrecision) {<br />
format = formatAndPrecision[1].toLowerCase();<br />
isCurrency = format === "c";<br />
isPercent = format === "p";<br />
if (isCurrency || isPercent) {<br />
//get specific number format information if format is currency or percent<br />
numberFormat = isCurrency ? numberFormat.currency : numberFormat.percent;<br />
groupSize = numberFormat.groupSize[0];<br />
groupSeparator = numberFormat[COMMA];<br />
decimal = numberFormat[POINT];<br />
precision = numberFormat.decimals;<br />
symbol = numberFormat.symbol;<br />
pattern = numberFormat.pattern[negative ? 0 : 1];<br />
}<br />
customPrecision = formatAndPrecision[2];<br />
if (customPrecision) {<br />
precision = +customPrecision;<br />
}<br />
//return number in exponential format<br />
if (format === "e") {<br />
return customPrecision ? number.toExponential(precision) : number.toExponential(); // toExponential() and toExponential(undefined) differ in FF #653438.<br />
}<br />
// multiply if format is percent<br />
if (isPercent) {<br />
number *= 100;<br />
}<br />
number = round(number, precision);<br />
negative = number < 0;<br />
number = number.split(POINT);<br />
integer = number[0];<br />
fraction = number[1];<br />
//exclude "-" if number is negative.<br />
if (negative) {<br />
integer = integer.substring(1);<br />
}<br />
value = integer;<br />
integerLength = integer.length;<br />
//add group separator to the number if it is longer enough<br />
if (integerLength >= groupSize) {<br />
value = EMPTY;<br />
for (idx = 0; idx < integerLength; idx++) {<br />
if (idx > 0 && (integerLength - idx) % groupSize === 0) {<br />
value += groupSeparator;<br />
}<br />
value += integer.charAt(idx);<br />
}<br />
}<br />
if (fraction) {<br />
value += decimal + fraction;<br />
}<br />
if (format === "n" && !negative) {<br />
return value;<br />
}<br />
number = EMPTY;<br />
for (idx = 0, length = pattern.length; idx < length; idx++) {<br />
ch = pattern.charAt(idx);<br />
if (ch === "n") {<br />
number += value;<br />
} else if (ch === "$" || ch === "%") {<br />
number += symbol;<br />
} else {<br />
number += ch;<br />
}<br />
}<br />
return number;<br />
}<br />
//custom formatting<br />
//<br />
//separate format by sections.<br />
//make number positive<br />
if (negative) {<br />
number = -number;<br />
}<br />
if (format.indexOf("'") > -1 || format.indexOf("\"") > -1 || format.indexOf("\\") > -1) {<br />
format = format.replace(literalRegExp, function (match) {<br />
var quoteChar = match.charAt(0).replace("\\", ""),<br />
literal = match.slice(1).replace(quoteChar, "");<br />
literals.push(literal);<br />
return PLACEHOLDER;<br />
});<br />
}<br />
format = format.split(";");<br />
if (negative && format[1]) {<br />
//get negative format<br />
format = format[1];<br />
hasNegativeFormat = true;<br />
} else if (number === 0) {<br />
//format for zeros<br />
format = format[2] || format[0];<br />
if (format.indexOf(SHARP) == -1 && format.indexOf(ZERO) == -1) {<br />
//return format if it is string constant.<br />
return format;<br />
}<br />
} else {<br />
format = format[0];<br />
}<br />
percentIndex = format.indexOf("%");<br />
currencyIndex = format.indexOf("$");<br />
isPercent = percentIndex != -1;<br />
isCurrency = currencyIndex != -1;<br />
//multiply number if the format has percent<br />
if (isPercent) {<br />
number *= 100;<br />
}<br />
if (isCurrency && format[currencyIndex - 1] === "\\") {<br />
format = format.split("<a href="file://\\").join">\\").join("");<br />
isCurrency = false;<br />
}<br />
if (isCurrency || isPercent) {<br />
//get specific number format information if format is currency or percent<br />
numberFormat = isCurrency ? numberFormat.currency : numberFormat.percent;<br />
groupSize = numberFormat.groupSize[0];<br />
groupSeparator = numberFormat[COMMA];<br />
decimal = numberFormat[POINT];<br />
precision = numberFormat.decimals;<br />
symbol = numberFormat.symbol;<br />
}<br />
hasGroup = format.indexOf(COMMA) > -1;<br />
if (hasGroup) {<br />
format = format.replace(commaRegExp, EMPTY);<br />
}<br />
decimalIndex = format.indexOf(POINT);<br />
length = format.length;<br />
if (decimalIndex != -1) {<br />
fraction = number.toString().split("e");<br />
if (fraction[1]) {<br />
fraction = round(number, Math.abs(fraction[1]));<br />
} else {<br />
fraction = fraction[0];<br />
}<br />
fraction = fraction.split(POINT)[1] || EMPTY;<br />
zeroIndex = format.lastIndexOf(ZERO) - decimalIndex;<br />
sharpIndex = format.lastIndexOf(SHARP) - decimalIndex;<br />
hasZero = zeroIndex > -1;<br />
hasSharp = sharpIndex > -1;<br />
idx = fraction.length;<br />
if (!hasZero && !hasSharp) {<br />
format = format.substring(0, decimalIndex) + format.substring(decimalIndex + 1);<br />
length = format.length;<br />
decimalIndex = -1;<br />
idx = 0;<br />
} if (hasZero && zeroIndex > sharpIndex) {<br />
idx = zeroIndex;<br />
} else if (sharpIndex > zeroIndex) {<br />
if (hasSharp && idx > sharpIndex) {<br />
idx = sharpIndex;<br />
} else if (hasZero && idx < zeroIndex) {<br />
idx = zeroIndex;<br />
}<br />
}<br />
if (idx > -1) {<br />
number = round(number, idx);<br />
}<br />
} else {<br />
number = round(number);<br />
}<br />
sharpIndex = format.indexOf(SHARP);<br />
startZeroIndex = zeroIndex = format.indexOf(ZERO);<br />
//define the index of the first digit placeholder<br />
if (sharpIndex == -1 && zeroIndex != -1) {<br />
start = zeroIndex;<br />
} else if (sharpIndex != -1 && zeroIndex == -1) {<br />
start = sharpIndex;<br />
} else {<br />
start = sharpIndex > zeroIndex ? zeroIndex : sharpIndex;<br />
}<br />
sharpIndex = format.lastIndexOf(SHARP);<br />
zeroIndex = format.lastIndexOf(ZERO);<br />
//define the index of the last digit placeholder<br />
if (sharpIndex == -1 && zeroIndex != -1) {<br />
end = zeroIndex;<br />
} else if (sharpIndex != -1 && zeroIndex == -1) {<br />
end = sharpIndex;<br />
} else {<br />
end = sharpIndex > zeroIndex ? sharpIndex : zeroIndex;<br />
}<br />
if (start == length) {<br />
end = start;<br />
}<br />
if (start != -1) {<br />
value = number.toString().split(POINT);<br />
integer = value[0];<br />
fraction = value[1] || EMPTY;<br />
integerLength = integer.length;<br />
fractionLength = fraction.length;<br />
if (negative && (number * -1) >= 0) {<br />
negative = false;<br />
}<br />
//add group separator to the number if it is longer enough<br />
if (hasGroup) {<br />
if (integerLength === groupSize && integerLength < decimalIndex - startZeroIndex) {<br />
integer = groupSeparator + integer;<br />
} else if (integerLength > groupSize) {<br />
value = EMPTY;<br />
for (idx = 0; idx < integerLength; idx++) {<br />
if (idx > 0 && (integerLength - idx) % groupSize === 0) {<br />
value += groupSeparator;<br />
}<br />
value += integer.charAt(idx);<br />
}<br />
integer = value;<br />
}<br />
}<br />
number = format.substring(0, start);<br />
if (negative && !hasNegativeFormat) {<br />
number += "-";<br />
}<br />
for (idx = start; idx < length; idx++) {<br />
ch = format.charAt(idx);<br />
if (decimalIndex == -1) {<br />
if (end - idx < integerLength) {<br />
number += integer;<br />
break;<br />
}<br />
} else {<br />
if (zeroIndex != -1 && zeroIndex < idx) {<br />
replacement = EMPTY;<br />
}<br />
if ((decimalIndex - idx) <= integerLength && decimalIndex - idx > -1) {<br />
number += integer;<br />
idx = decimalIndex;<br />
}<br />
if (decimalIndex === idx) {<br />
number += (fraction ? decimal : EMPTY) + fraction;<br />
idx += end - decimalIndex + 1;<br />
continue;<br />
}<br />
}<br />
if (ch === ZERO) {<br />
number += ch;<br />
replacement = ch;<br />
} else if (ch === SHARP) {<br />
number += replacement;<br />
}<br />
}<br />
if (end >= start) {<br />
number += format.substring(end + 1);<br />
}<br />
</script>