Le format consiste à convertir tout type de données en une chaîne via des opérations de format. Par exemple, ce qui suit
La copie de code est la suivante:
<cript>
console.log (chopper.format ('{0} - {1} - {2}', 12, 24, 25)); // Sorties "12 - 24 - 25"
</cript>
Voici un code complet qui peut être copié dans votre propre projet.
La copie de code est la suivante:
<! Doctype html>
<html>
<adal>
<meta http-equiv = "contenu-type" contenu = "text / html; charset = utf-8">
</ head>
<body>
<script src = "http://code.jquery.com/jquery-1.9.1.min.js"> </ script>
<cript>
(fonction() {
var chopper = window.chopper = window.chopper || {cultures: {}},
math = math,
formatregexp = // {(/ d +) (: [^ /}] +)? /} / g,
Function = "fonction",
String = "String",
Numéro = "nombre",
Object = "objet",
Null = "null",
Booléen = "booléen",
Undefined = "Undefined",
tranche = [] .slice,
globaliser = window.globalize,
StandardFormatRegexp = / ^ (n | c | p | e) (/ d *) $ / i,
litteralRegexp = /(//.)|(ature est-il.
CommareGexp = //, / g,
Vide = "",
Point = ".",
Virgule = ",",
Sharp = "#",
Zéro = "0",
Placeholder = "??",
En = "en-us",
objectToString = {} .toString;
// cultures
Chopper.Cultures ["en-us"] = {
Nom: en,
NumberFormat: {
motif: ["-n"],
décimales: 2,
",": ",",
".": ".",
GroupeSize: [3],
pourcentage: {
modèle: ["-n%", "n%"],
décimales: 2,
",": ",",
".": ".",
GroupeSize: [3],
symbole: "%"
},
devise: {
modèle: ["($ n)", "$ n"],
décimales: 2,
",": ",",
".": ".",
GroupeSize: [3],
Symbole: "$"
}
},
Calendriers: {
standard: {
jours: {
Noms: ["Sunday", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"],
namesAbbr: ["Sun", "Mon", "mar", "Wed", "Thu", "Fri", "Sat"],
nameshort: ["su", "mo", "tu", "we", "th", "fr", "sa"]
},
mois: {
Noms: ["January", "Février", "March", "April", "May", "June", "Juillet", "Juillet", "August", "Septembre", "Octobre", "Novembre", "Décembre"],
namesabbr: ["jan", "février", "mar", "avr", "mai", "juin", "juil", "août", "sept", "oct", "nov", "dec"]
},
AM: ["Am", "Am", "Am"],
PM: ["PM", "PM", "PM"],
motifs: {
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",
m: "mmmm dd",
M: "mmmm dd",
S: "Yyyy '-' mm '-' ddthh ':' mm ':' ss",
T: "H: MM TT",
T: "H: MM: SS TT",
U: "Yyyy '-' MM '-' DD HH ':' MM ':' SS'Z '",
Y: "Mmmm, Yyyy",
Y: "Mmmm, Yyyy"
},
"/": "/",
":": ":",
Premier jour: 0,
TwodigityEarmax: 2029
}
}
};
fonction FindCulture (culture) {
if (culture) {
if (Culture.numberformat) {
retour de la culture;
}
if (typeof Culture === String) {
Var Cultures = Chopper.Cultures;
RETOUR Cultures [Culture] || cultures [culture.split ("-") [0]] || nul;
}
retourner null;
}
retourner null;
}
fonction getCulture (culture) {
if (culture) {
Culture = FindCulture (culture);
}
Retour Culture || Chopper.Cultures.Current;
}
fonction extendNumberFormat (NumberFormat) {
NumberFormat.GroupSizes = NumberFormat.GroupSize;
NumberFormat.percent.GroupSizes = NumberFormat.percent.GroupSize;
NumberFormat.Currency.GroupSizes = NumberFormat.Currency.GroupSize;
}
Chopper.Culture = fonction (Culturename) {
Var Cultures = Chopper.Cultures, Culture;
if (culturename! == Undefined) {
Culture = FindCulture (Culturename) || cultures [en];
Culture.Calendar = Culture.Calendar.Standard;
cultures.current = culture;
if (globaliser &&! Globalize.load) {
ExtendNumberFormat (Culture.numberformat);
}
} autre {
Cultures de retour.Current;
}
};
Chopper.Culture (en);
// Formatage des nombres
Fonction FormatNumber (nombre, format, culture) {
culture = getCulture (culture);
var numberformat = culture.numberformat,
groupSize = NumberFormat.GroupSize [0],
groupSeparator = NumberFormat [Comma],
Decimal = NumberFormat [point],
precision = numberformat.decimals,
motive = numberformat.pattern [0],
littéraux = [],
symbole,
Iscurrence, Ispercent,
Customprécision,
formatandprécision,
négatif = nombre <0,
entier,
fraction,
IntegerLength,
FractionLength,
Remplacement = vide,
valeur = vide,
idx,
longueur,
ch,
Hasgroup,
HasnegativeFormat,
décimalindex,
Sharpindex,
zéroIndex,
Haszero, Hassharp,
pour cent,
CurrencyIndex,
startZeroIndex,
démarrer = -1,
fin;
// retourne la chaîne vide si pas de numéro
if (nombre === Undefined) {
retour vide;
}
if (! isfinite (numéro)) {
numéro de retour;
}
// Si pas de format, retournez NUBER.TOSTRING () ou NUBER.TOLOCALESTRING () Si Culture.name n'est pas défini
if (! format) {
return culture.name.length? Number.tolocalestring (): numéro.toString ();
}
formatandPrecision = standardformatRegexp.exec (format);
// Formatage standard
if (formatandprécision) {
format = formatandprécision [1] .tolowerCase ();
isCurrency = format === "C";
Ispercent = format === "P";
if (isCurrency || Ispercent) {
// Obtenez des informations de format de nombre spécifiques si le format est de la devise ou du pourcentage
NumberFormat = isCurrency? NumberFormat.Currency: NumberFormat.percent;
groupSize = NumberFormat.GroupSize [0];
groupSeparator = NumberFormat [Comma];
Decimal = NumberFormat [Point];
precision = numberformat.decimals;
symbol = numberformat.Symbol;
Pattern = NumberFormat.Pattern [négatif? 0: 1];
}
CustomPrecision = FormatandPrecision [2];
if (custompricision) {
Precision = + CustomPrecision;
}
// Numéro de retour au format exponentiel
if (format === "e") {
retourner CustomPrecision? Number.toExponential (précision): numéro.toexponential (); // toexponential () et toexponentiel (non défini) différent dans FF # 653438.
}
// Multipliez si le format est en pourcentage
if (ispercent) {
nombre * = 100;
}
nombre = rond (nombre, précision);
négatif = nombre <0;
Number = Number.Split (point);
entier = nombre [0];
fraction = nombre [1];
// Exclure "-" Si le nombre est négatif.
if (négatif) {
Integer = Integer.SubString (1);
}
valeur = entier;
IntegerLength = Integer.Length;
// Ajouter un séparateur de groupe au nombre s'il est suffisamment plus long
if (IntegerLength> = GroupSize) {
valeur = vide;
pour (idx = 0; idx <IntegerLength; idx ++) {
if (idx> 0 && (IntegerLength - idx)% groupSize === 0) {
Valeur + = GroupSeparator;
}
Valeur + = Integer.Charat (idx);
}
}
if (fraction) {
valeur + = décimal + fraction;
}
if (format === "n" &&! négatif) {
valeur de retour;
}
nombre = vide;
pour (idx = 0, longueur = motif.length; idx <longueur; idx ++) {
ch = motive.charat (idx);
if (ch === "n") {
nombre + = valeur;
} else if (ch === "$" || ch === "%") {
nombre + = symbole;
} autre {
nombre + = ch;
}
}
numéro de retour;
}
// Formatage personnalisé
//
// Format séparé par sections.
// rendre le nombre positif
if (négatif) {
nombre = -number;
}
if (format.indexof ("'")> -1 || format.indexof ("/" ")> -1 || format.indexof (" // ")> -1) {
format = format.replace (litteralregexp, fonction (match) {
var qutechar = match.charat (0) .replace ("//", ""),
littéral = match.slice (1) .replace (quottechar, "");
littéraux.push (littéral);
Retour Placeholder;
});
}
format = format.split (";");
if (négatif && format [1]) {
// Obtenez un format négatif
format = format [1];
HasnegativeFormat = true;
} else if (nombre === 0) {
// Format pour zéros
format = format [2] || format [0];
if (format.indexof (sharp) == -1 && format.indexof (zéro) == -1) {
// RETOUR FORMAT Si c'est constant string.
format de retour;
}
} autre {
format = format [0];
}
pour perdindex = format.indexof ("%");
CurrencyIndex = format.Indexof ("$");
Ispercent = pour cent! = -1;
isCurrency = CurrencyIndex! = -1;
// multiplier le nombre si le format a pourcentage
if (ispercent) {
nombre * = 100;
}
if (isCurrency && format [CurrencyIndex - 1] === "//") {
format = format.split ("//"). join ("");
isCurrency = false;
}
if (isCurrency || Ispercent) {
// Obtenez des informations de format de nombre spécifiques si le format est de la devise ou du pourcentage
NumberFormat = isCurrency? NumberFormat.Currency: NumberFormat.percent;
groupSize = NumberFormat.GroupSize [0];
groupSeparator = NumberFormat [Comma];
Decimal = NumberFormat [Point];
precision = numberformat.decimals;
symbol = numberformat.Symbol;
}
HasGroup = format.indexof (virgule)> -1;
if (hasgroup) {
format = format.replace (CommareGExp, vide);
}
decimalindex = format.indexof (point);
longueur = format.length;
if (decimalindex! = -1) {
fraction = nombre.toString (). Split ("E");
if (fraction [1]) {
fraction = rond (nombre, math.abs (fraction [1]));
} autre {
fraction = fraction [0];
}
fraction = fraction.split (point) [1] || VIDE;
zeroIndex = format.LastIndexof (zéro) - 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);
longueur = format.length;
DECIMALINDEX = -1;
idx = 0;
} if (haszero && zeroIndex> sharpindex) {
idx = zeroIndex;
} else if (sharpindex> zeroIndex) {
if (hassharp && idx> sharpindex) {
idx = sharpindex;
} else if (haszero && idx <zeroIndex) {
idx = zeroIndex;
}
}
if (idx> -1) {
numéro = rond (nombre, idx);
}
} autre {
nombre = rond (nombre);
}
SharpIndex = format.indexof (Sharp);
startZeroIndex = zeroIndex = format.indexof (zéro);
// Définissez l'indice de l'espace réservé au premier chiffre
if (SharpIndex == -1 && zeroIndex! = -1) {
start = zeroIndex;
} else if (SharpIndex! = -1 && zeroIndex == -1) {
start = sharpindex;
} autre {
start = sharpindex> zeroIndex? ZeroIndex: Sharpindex;
}
SharpIndex = format.LastIndexof (Sharp);
zeroIndex = format.LastIndexof (zéro);
// Définissez l'indice de l'espace réservé au dernier chiffre
if (SharpIndex == -1 && zeroIndex! = -1) {
end = zeroIndex;
} else if (SharpIndex! = -1 && zeroIndex == -1) {
end = sharpindex;
} autre {
end = sharpindex> zeroIndex? Sharpindex: zeroIndex;
}
if (start == longueur) {
end = start;
}
if (start! = -1) {
Value = Number.ToString (). Split (point);
entier = valeur [0];
fraction = valeur [1] || VIDE;
IntegerLength = Integer.Length;
fractionLength = fraction.length;
if (négatif && (nombre * -1)> = 0) {
négatif = false;
}
// Ajouter un séparateur de groupe au nombre s'il est suffisamment plus long
if (hasgroup) {
if (IntegerLength === GROUPSIZE && IntegerLength <decimalindex - startzeroIndex) {
Integer = GroupSeparator + Integer;
} else if (IntegerLength> GroupSize) {
valeur = vide;
pour (idx = 0; idx <IntegerLength; idx ++) {
if (idx> 0 && (IntegerLength - idx)% groupSize === 0) {
Valeur + = GroupSeparator;
}
Valeur + = Integer.Charat (idx);
}
entier = valeur;
}
}
nombre = format.substring (0, start);
if (négatif &&! HasnegativeFormat) {
nombre + = "-";
}
pour (idx = start; idx <longueur; idx ++) {
ch = format.charat (idx);
if (decimalindex == -1) {
if (end - idx <IntegerLength) {
nombre + = entier;
casser;
}
} autre {
if (zeroIndex! = -1 && zeroIndex <idx) {
remplacement = vide;
}
if ((decimalindex - idx) <= IntegerLength && decimalindex - idx> -1) {
nombre + = entier;
idx = decimalindex;
}
if (decimalindex === idx) {
nombre + = (fraction? décimal: vide) + fraction;
idx + = end - DECIMALINDEX + 1;
continuer;
}
}
if (ch === zéro) {
nombre + = ch;
remplacement = ch;
} else if (ch === Sharp) {
nombre + = remplacement;
}
}
if (end> = start) {
nombre + = format.substring (end + 1);
}
// remplacer les espaces réservés des symboles
if (isCurrency || Ispercent) {
valeur = vide;
pour (idx = 0, longueur = nombre.length; idx <longueur; idx ++) {
ch = nombre.charat (idx);
valeur + = (ch === "$" || ch === "%")? Symbole: Ch;
}
Numéro = valeur;
}
longueur = littéraux.lengle;
if (longueur) {
pour (idx = 0; idx <longueur; idx ++) {
Numéro = Number.replace (placeholder, littéraux [idx]);
}
}
}
numéro de retour;
}
var round = fonction (valeur, précision) {
précision = précision || 0;
valeur = valeur.toString (). Split ('e');
valeur = math.round (+ (valeur [0] + 'e' + (valeur [1]? (+ valeur [1] + précision): précision)));
valeur = valeur.toString (). Split ('e');
valeur = + (valeur [0] + 'e' + (valeur [1]? (+ valeur [1] - précision): -précision));
return value.tofixed (précision);
};
var toString = fonction (valeur, fmt, culture) {
if (fmt) {
if (typeof value === numéro) {
Retour FormatNumber (valeur, FMT, culture);
}
}
Valeur de retour! == Undefined? valeur : "";
};
if (globaliser &&! Globalize.load) {
toString = fonction (valeur, format, culture) {
if ($ .isplainObject (culture)) {
Culture = Culture.Name;
}
Retour Globalize.format (valeur, format, culture);
};
}
Chopper.format = fonction (fmt) {
var valeurs = arguments;
return fmt.replace (formatregexp, fonction (match, index, placeholderFormat) {
Var valeur = valeurs [parseInt (index, 10) + 1];
return toString (valeur, placeholderFormat? PlanholderFormat.Substring (1): "");
});
};
}) ();
</cript>
</docy>
</html>
API:
La copie de code est la suivante:
Chopper.format ('{0} joue {1}', 'XiaoMing', 'Basketball'); // produit "XiaoMing joue au basket"
// prix
chopper.format ('{0: c} - {1: c}', 10, 20); // Sortie "10,00−20,00"
// index
Chopper.format ('index: {0: e}', 25); // Sorties "Index: 2.5e + 1"
// pour cent
Chopper.format ('pour cent: {0: p}', 25); // produit "pourcentage: 2500,00%"
// décimal
Chopper.format ('Decimal: {0: n}', 25); // produit "décimal: 25.00"
résumé:
Les données de format sont souvent utilisées dans le développement. Par exemple, nous devons provoquer différentes informations en fonction des variables, mais les modèles de contenu sont les mêmes, nous pouvons donc utiliser cette méthode. Si votre projet utilise jQuery, vous pouvez également encapsuler le javascript ci-dessus dans un plugin jQuery.