Формат предназначен для преобразования любого типа данных в строку через операции формата. Например, следующее
Кода -копия выглядит следующим образом:
<Скрипт>
console.log (Chopper.format ('{0} - {1} - {2}', 12, 24, 25, 25)); // выходы "12 - 24 - 25"
</script>
Вот полный код, который можно скопировать в ваш собственный проект.
Кода -копия выглядит следующим образом:
<! Doctype html>
<html>
<голова>
<meta http-equiv = "content-type" content = "text/html; charset = utf-8">
</head>
<тело>
<script src = "http://code.jquery.com/jquery-1.9.1.min.js"> </script>
<Скрипт>
(function () {
var Chopper = window.chopper = window.chopper || {культуры: {}},
математика = математика,
formatregexp = // {(/d+) (: [^/}]+)?/}/g,
Function = "function",
String = "string",
Номер = "номер",
Object = "Object",
Null = "null",
Boolean = "boolean",
Undefined = "не определен",
slice = [] .slice,
Globalize = window.globalize,
StandardFormatRegexp =/^(n | C | P | E) (/D*) $/i,
LiteralRegexp = /(///.)|мас
commaregexp = //,/g,
Пусто = "",
Точка = ".",
Comma = ",",
Sharp = "#",
Zero = "0",
Placeholder = "??",
En = "en-us",
ObjectToString = {} .toString;
// культуры
Chopper.cultures ["en-us"] = {
имя: en,
numberFormat: {
шаблон: ["-n"],
Десятичные: 2,
",": ",",
".": ".",
Groupize: [3],
Процент: {
шаблон: ["-n %", "n %"],
Десятичные: 2,
",": ",",
".": ".",
Groupize: [3],
Символ: "%"
},
валюта: {
шаблон: ["($ n)", "$ n"],
Десятичные: 2,
",": ",",
".": ".",
Groupize: [3],
Символ: "$"
}
},
Календари: {
Стандарт: {
Дни: {
Имена: [«Воскресенье», «Понедельник», «Вторник», «Среда», «Четверг», «Пятница», «Суббота»],
namesabbr: [«Солнце», «Мон», «Вт», «Ср», «Чт», «Пт», «Сб»],
Namesshort: ["su", "mo", "tu", "мы", "th", "fr", "sa"]
},
месяцы: {
Имена: [«Январь», «февраль», «март», «апрель», «май», «июнь», «июль», «июль», «Август», «Сентябрь», «Октябрь», «Ноябрь», «Декабрь»],
namesabbr: [«Ян», «февраль», «Мар», «Апр», «Мэй», «Джун», «Юл», «Авг», «СЕП», «Октябрь», «Новый», «Дек дек»]
},
AM: ["Am", "Am", "Am"],
PM: ["PM", "PM", "PM"],
шаблоны: {
D: "m/d/yyyy",
D: "DDDD, MMMM DD, YYYY",
F: "DDDD, MMMM DD, YYYY H: MM: SS TT",
G: "M/D/Yyyy H: MM TT",
G: "M/D/Yyyy H: MM: SS TT",
м: "мммм дд",
М: "мммм дд",
S: "yyyy '-' mm '-' ddthh ':' mm ':' ss",
T: "H: MM TT",
T: "H: MM: SS TT",
u: "yyyy '-' mm '-' dd hh ':' mm ':' ss'z '",
y: "Мммм, ты
Y: "Мммм, ты
},
"/": "/",
":": ":",
первый день: 0,
TwodigityearMax: 2029
}
}
};
Функция Findculture (культура) {
if (культура) {
if (culture.numberformat) {
культура возвращения;
}
if (typeof culture === String) {
VAR Cultures = Chopper.cultures;
Возвращение культуры [культура] || культуры [culture.split ("-") [0]] || нулевой;
}
вернуть ноль;
}
вернуть ноль;
}
функция getCulture (культура) {
if (культура) {
культура = FindCulture (культура);
}
культура возвращения || Chopper.cultures.current;
}
функция ExpandNumberFormat (NumberFormat) {
numberFormat.GroupSizes = numberFormat.GroupSize;
numberFormat.percent.GroupSizes = numberFormat.percent.GroupSize;
numberFormat.currency.GroupSizes = numberFormat.currency.GroupSize;
}
Chopper.culture = function (cultureneMeame) {
VAR Cultures = Чоппер. Культуры, культура;
if (culturename! == не определено) {
Культура = FindCulture (CulturenEmeme) || культуры [en];
Culture.calendar = culture.calendars.standard;
культуры.current = культура;
if (globalize &&! globalize.load) {
ExpandNumberFormat (Culture.NumberFormat);
}
} еще {
вернуть культуры.
}
};
Chopper.culture (en);
// форматирование номера
Функция Formatnumber (число, формат, культура) {
культура = getCulture (культура);
var numberformat = culture.numberformat,
Groupize = numberFormat.GroupSize [0],
GroupSeParator = numberFormat [comma],
Decimal = numberFormat [point],
precision = numberFormat.decimals,
pattern = numberFormat.pattern [0],
литералы = [],
символ,
Икламуна, Ispercent,
пользовательская,
FormatandPrecision,
отрицательный = номер <0,
целое число,
фракция,
IntegerLength,
длина длина,
замена = пусто,
значение = пусто,
idx,
длина,
ch,
hasgroup,
HasnegativeFormat,
децималиндекс,
Sruprindex,
Zeroindex,
HASCREO, Hassharp,
процентиндекс,
currencyIndex,
startzeroindex,
Start = -1,
конец;
// возвращать пустую строку, если нет номера
if (число === не определено) {
вернуть пусто;
}
if (! Isfinite (номер)) {
возвратный номер;
}
// Если нет формата, то return number.tostring () или number.tolocalestring (), если культура.
if (! format) {
return culture.name.length? number.tolocalestring (): number.tostring ();
}
FormatAndPrecision = StandardFormatRegexp.exec (format);
// Стандартное форматирование
if (formatandprecision) {
format = formatandprecision [1] .tolowercase ();
iscurrency = format === "c";
ispercent = format === "p";
if (iscurrange || ispercent) {
// Получить конкретную информацию о формате чисел, если формат валюта или процент
numberFormat = iscurrency? NumberFormat.currency: numberFormat.percent;
Groupize = numberFormat.GroupSize [0];
GroupSeParator = numberFormat [comp];
Decimal = numberFormat [point];
precision = numberformat.decimals;
Symbol = numberFormat.syMbol;
pattern = numberFormat.pattern [отрицательный? 0: 1];
}
CustomPrecision = FormatandPrecision [2];
if (CustomPrecision) {
precision = +customprecision;
}
// возвратный номер в экспоненциальном формате
if (format === "e") {
вернуть Custompresity? number.toexponential (precision): number.toexponential (); // toexponential () и toexponential (неопределенное) отличается от FF #653438.
}
// умножьте, если формат составляет процент
if (iSpercent) {
номер *= 100;
}
число = раунд (число, точность);
отрицательный = число <0;
number = number.split (point);
integer = число [0];
Фракция = число [1];
// исключить "-" Если число отрицательное.
if (отрицательный) {
integer = integer.substring (1);
}
значение = целое число;
integerlength = integer.length;
// Добавить групповой сепаратор к номеру, если он достаточно дольше
if (integerlength> = Grignize) {
значение = пусто;
for (idx = 0; idx <integerlength; idx ++) {
if (idx> 0 && (integerlength - idx) % Groupize === 0) {
значение += GroupSeParator;
}
значение += integer.charat (idx);
}
}
if (fraction) {
Значение + = Десятичная + Фракция;
}
if (format === "n" &&! Oftion) {
возвращаемое значение;
}
номер = пусто;
for (idx = 0, length = pattern.length; idx <length; idx ++) {
ch = pattern.charat (idx);
if (ch === "n") {
число += значение;
} else if (ch === "$" || ch === "%") {
номер += символ;
} еще {
номер += CH;
}
}
возвратный номер;
}
// пользовательское форматирование
//
// отдельный формат по разделам.
// Сделать номер положительным
if (отрицательный) {
номер = -number;
}
if (format.indexof ("'")> -1 || format.indexof ("/" ")> -1 || format.indexof (" // ")> -1) {
format = format.replace (LiteralRegexp, function (match) {
var quotechar = match.charat (0) .replace ("//", ""),
Literal = match.slice (1) .Replace (quoteChar, "");
Литералы. Пуш (буквальный);
возврат заполнителя;
});
}
format = format.split (";");
if (отрицательный && format [1]) {
// Получить отрицательный формат
format = format [1];
hasnegativeformat = true;
} else if (number === 0) {
// формат для нулей
format = format [2] || формат [0];
if (format.indexof (sharp) == -1 && format.indexof (Zero) == -1) {
// возвращать формат, если он постоянный строка.
возврат формат;
}
} еще {
format = format [0];
}
процентиндекс = format.indexof ("%");
currencyIndex = format.indexof ("$");
ispercent = процентиндекс! = -1;
iscurrence = currencyIndex! = -1;
// Умножение числа, если в формате есть процент
if (iSpercent) {
номер *= 100;
}
if (iscurrency && format [currencyIndex - 1] === "//") {
format = format.split ("//"). join ("");
IScurrency = false;
}
if (iscurrange || ispercent) {
// Получить конкретную информацию о формате чисел, если формат валюта или процент
numberFormat = iscurrency? NumberFormat.currency: numberFormat.percent;
Groupize = numberFormat.GroupSize [0];
GroupSeParator = numberFormat [comp];
Decimal = numberFormat [point];
precision = numberformat.decimals;
Symbol = numberFormat.syMbol;
}
hasgroup = format.indexof (запятая)> -1;
if (hasgroup) {
format = format.replace (commaregexp, пусто);
}
decimalindex = format.indexof (point);
длина = format.length;
if (decimalindex! = -1) {
fraction = number.toString (). Split ("e");
if (fraction [1]) {
Фракция = раунд (номер, математика.
} еще {
Фракция = Фракция [0];
}
fraction = fraction.split (точка) [1] || ПУСТОЙ;
ZeroIndex = format.lastIndexof (Zero) - decimalIndex;
Sharpindex = format.lastIndexof (Sharp) - DecimalIndex;
haszero = ZeroIndex> -1;
hassharp = sharpindex> -1;
idx = fraction.length;
if (! haszero &&! hassharp) {
format = format.substring (0, decimalindex) + format.substring (decimalindex + 1);
длина = format.length;
decimalindex = -1;
idx = 0;
} if (haszero && ZeroIndex> Spirpindex) {
idx = ZeroIndex;
} else if (spirpindex> ZeroIndex) {
if (hassharp && idx> swarpindex) {
idx = sharpindex;
} else if (haszero && idx <ZeroIndex) {
idx = ZeroIndex;
}
}
if (idx> -1) {
номер = раунд (номер, idx);
}
} еще {
число = раунд (номер);
}
SpartIndex = format.indexof (Sharp);
startRecroIndex = ZeroIndex = format.indexof (Zero);
// Определите индекс первой цифровой заполнители
if (swarpindex == -1 && ZeroIndex! = -1) {
start = ZeroIndex;
} else if (swarpindex! = -1 && ZeroIndex == -1) {
start = sharpindex;
} еще {
start = sharpindex> ZeroIndex? ZeroIndex: Sruckindex;
}
SpartIndex = format.lastIndexof (Sharp);
ZeroIndex = format.lastindexof (Zero);
// Определите индекс последней цифровой заполнители
if (swarpindex == -1 && ZeroIndex! = -1) {
end = ZeroIndex;
} else if (swarpindex! = -1 && ZeroIndex == -1) {
end = sharpindex;
} еще {
end = sharpindex> ZeroIndex? Sruckindex: ZeroIndex;
}
if (start == length) {
end = start;
}
if (start! = -1) {
value = number.toString (). Split (point);
integer = value [0];
Фракция = значение [1] || ПУСТОЙ;
integerlength = integer.length;
fractionLength = fraction.length;
if (отрицательный && (номер * -1)> = 0) {
отрицательный = false;
}
// Добавить групповой сепаратор к номеру, если он достаточно дольше
if (hasgroup) {
if (integerlength === Groupize && Integerlength <decimalindex - startzeroIndex) {
Integer = GroupSeParator + Integer;
} else if (integerlength> Grignize) {
значение = пусто;
for (idx = 0; idx <integerlength; idx ++) {
if (idx> 0 && (integerlength - idx) % Groupize === 0) {
значение += GroupSeParator;
}
значение += integer.charat (idx);
}
integer = значение;
}
}
number = format.substring (0, start);
if (негативное &&! hasnegativeformat) {
номер += "-";
}
for (idx = start; idx <length; idx ++) {
ch = format.charat (idx);
if (decimalindex == -1) {
if (end - idx <integerlength) {
число += целое число;
перерыв;
}
} еще {
if (ZeroIndex! = -1 && ZeroIndex <idx) {
замена = пусто;
}
if (((decimalindex - idx) <= integerlength && decimalindex - idx> -1) {
число += целое число;
idx = decimalindex;
}
if (decimalindex === idx) {
число + = (дробь? Десятичная: пусто) + дробь;
idx + = end - decimalindex + 1;
продолжать;
}
}
if (ch === Zero) {
номер += CH;
замена = CH;
} else if (ch === sharp) {
номер += замена;
}
}
if (end> = start) {
число + = format.substring (end + 1);
}
// заменить символы заполнителей
if (iscurrange || ispercent) {
значение = пусто;
for (idx = 0, length = number.length; idx <length; idx ++) {
ch = number.charat (idx);
Значение += (CH === "$" || CH === "%")? Символ: Ch;
}
number = value;
}
длина = литералы.
if (длина) {
for (idx = 0; idx <length; idx ++) {
number = number.replace (Placeholder, Literals [idx]);
}
}
}
возвратный номер;
}
var Round = function (значение, точность) {
точность = точность || 0;
value = value.toString (). Split ('e');
value = math.round ( + (value [0] + 'e' + (value [1]? ( + value [1] + precision): precision)));
value = value.toString (). Split ('e');
value = + (value [0] + 'E' + (значение [1]? ( + value [1] - precision): -precision));
return value.tofixed (точность);
};
var toString = function (значение, FMT, культура) {
if (fmt) {
if (typeof value === number) {
возврат форматнобеля (значение, FMT, культура);
}
}
возвращаемое значение! == не определено? ценить : "";
};
if (globalize &&! globalize.load) {
toString = function (значение, формат, культура) {
if ($ .isplainObject (культура)) {
культура = культура. name;
}
return globalize.format (значение, формат, культура);
};
}
Chopper.format = function (fmt) {
var values = аргументы;
return fmt.replace (formatregexp, function (match, index, placeholderformat) {
var value = values [parseint (index, 10) + 1];
return toString (значение, PlaceholderFormat? PlaceholderFormat.substring (1): "");
});
};
}) ();
</script>
</body>
</html>
API:
Кода -копия выглядит следующим образом:
Chopper.format ('{0} играет {1}', 'Xiaoming', 'Basketball'); // выводы "Сяоминг играет в баскетбол"
// цена
Chopper.format ('{0: c} - {1: c}', 10, 20); // выводы "10.00–20,00"
// Индекс
Chopper.format ('index: {0: e}', 25); // выходы "Индекс: 2,5e+1"
// процент
Chopper.format ('процент: {0: p}', 25); // выводы "Процент: 2500,00 %"
// Десятичный
Chopper.format ('Decimal: {0: n}', 25); // выводы "Десятичный: 25,00"
краткое содержание:
Данные формата часто используются в разработке. Например, нам необходимо предоставить различную информацию в соответствии с переменными, но шаблоны содержимого одинаковы, поэтому мы можем использовать этот метод. Если ваш проект использует jQuery, вы также можете инкапсулировать вышеуказанный JavaScript в плагин jQuery.