2017-07-28 20:24:37 +00:00
|
|
|
function choose_fmt(f/*:string*/, v/*:any*/) {
|
2017-03-21 07:45:12 +00:00
|
|
|
var fmt = split_fmt(f);
|
|
|
|
var l = fmt.length, lat = fmt[l-1].indexOf("@");
|
|
|
|
if(l<4 && lat>-1) --l;
|
|
|
|
if(fmt.length > 4) throw new Error("cannot find right format for |" + fmt.join("|") + "|");
|
|
|
|
if(typeof v !== "number") return [4, fmt.length === 4 || lat>-1?fmt[fmt.length-1]:"@"];
|
2024-04-27 23:49:12 +00:00
|
|
|
/* NOTE: most spreadsheet software do not support NaN or infinities */
|
|
|
|
if(typeof v === "number" && !isFinite(v)) v = 0;
|
2017-03-21 07:45:12 +00:00
|
|
|
switch(fmt.length) {
|
|
|
|
case 1: fmt = lat>-1 ? ["General", "General", "General", fmt[0]] : [fmt[0], fmt[0], fmt[0], "@"]; break;
|
|
|
|
case 2: fmt = lat>-1 ? [fmt[0], fmt[0], fmt[0], fmt[1]] : [fmt[0], fmt[1], fmt[0], "@"]; break;
|
|
|
|
case 3: fmt = lat>-1 ? [fmt[0], fmt[1], fmt[0], fmt[2]] : [fmt[0], fmt[1], fmt[2], "@"]; break;
|
|
|
|
case 4: break;
|
|
|
|
}
|
|
|
|
var ff = v > 0 ? fmt[0] : v < 0 ? fmt[1] : fmt[2];
|
|
|
|
if(fmt[0].indexOf("[") === -1 && fmt[1].indexOf("[") === -1) return [l, ff];
|
|
|
|
if(fmt[0].match(cfregex) != null || fmt[1].match(cfregex) != null) {
|
|
|
|
var m1 = fmt[0].match(cfregex2);
|
|
|
|
var m2 = fmt[1].match(cfregex2);
|
|
|
|
return chkcond(v, m1) ? [l, fmt[0]] : chkcond(v, m2) ? [l, fmt[1]] : [l, fmt[m1 != null && m2 != null ? 2 : 1]];
|
|
|
|
}
|
|
|
|
return [l, ff];
|
|
|
|
}
|
|
|
|
function format(fmt/*:string|number*/,v/*:any*/,o/*:?any*/) {
|
2017-04-30 04:54:41 +00:00
|
|
|
if(o == null) o = {};
|
2017-03-21 07:45:12 +00:00
|
|
|
var sfmt = "";
|
|
|
|
switch(typeof fmt) {
|
2017-04-30 04:54:41 +00:00
|
|
|
case "string":
|
|
|
|
if(fmt == "m/d/yy" && o.dateNF) sfmt = o.dateNF;
|
|
|
|
else sfmt = fmt;
|
|
|
|
break;
|
|
|
|
case "number":
|
|
|
|
if(fmt == 14 && o.dateNF) sfmt = o.dateNF;
|
|
|
|
else sfmt = (o.table != null ? (o.table/*:any*/) : table_fmt)[fmt];
|
2020-06-17 05:13:59 +00:00
|
|
|
if(sfmt == null) sfmt = (o.table && o.table[default_map[fmt]]) || table_fmt[default_map[fmt]];
|
|
|
|
if(sfmt == null) sfmt = default_str[fmt] || "General";
|
2017-04-30 04:54:41 +00:00
|
|
|
break;
|
2017-03-21 07:45:12 +00:00
|
|
|
}
|
|
|
|
if(isgeneral(sfmt,0)) return general_fmt(v, o);
|
2017-07-28 20:24:37 +00:00
|
|
|
if(v instanceof Date) v = datenum_local(v, o.date1904);
|
2017-03-21 07:45:12 +00:00
|
|
|
var f = choose_fmt(sfmt, v);
|
|
|
|
if(isgeneral(f[1])) return general_fmt(v, o);
|
|
|
|
if(v === true) v = "TRUE"; else if(v === false) v = "FALSE";
|
|
|
|
else if(v === "" || v == null) return "";
|
2024-07-04 19:54:34 +00:00
|
|
|
else if(isNaN(v) && f[1].indexOf("0") > -1) return "#NUM!";
|
2024-04-27 23:49:12 +00:00
|
|
|
else if(!isFinite(v) && f[1].indexOf("0") > -1) return "#DIV/0!";
|
2017-03-21 07:45:12 +00:00
|
|
|
return eval_fmt(f[1], v, o, f[0]);
|
|
|
|
}
|