Javascript 版本的 Sprintf 字符串格式化函数

转载 2007年09月19日 10:27:00
/*
** sprintf.js -- POSIX sprintf(3) style formatting function for JavaScript
** Copyright (c) 2006-2007 Ralf S. Engelschall <rse@engelschall.com>
** Partly based on Public Domain code by Jan Moesen <http://jan.moesen.nu/>
** Licensed under GPL <http://www.gnu.org/licenses/gpl.txt>
**
** $LastChangedDate$
** $LastChangedRevision$
*/

/* make sure the ECMAScript 3.0 Number.toFixed() method is available */
if (typeof Number.prototype.toFixed != "undefined") {
(function(){
/* see http://www.jibbering.com/faq/#FAQ4_6 for details */
function Stretch(Q, L, c) {
var S = Q
if (c.length > 0)
while (S.length < L)
S = c+S;
return S;
}
function StrU(X, M, N) { /* X >= 0.0 */
var T, S;
S = new String(Math.round(X * Number("1e"+N)));
if (S.search && S.search(//D/) != -1)
return ''+X;
with (new String(Stretch(S, M+N, '0')))
return substring(0, T=(length-N)) + '.' + substring(T);
}
function Sign(X) {
return X < 0 ? '-' : '';
}
function StrS(X, M, N) {
return Sign(X)+StrU(Math.abs(X), M, N);
}
Number.prototype.toFixed = function (n) { return StrS(this, 1, n) };
})();
}

/* the sprintf() function */
sprintf = function () {
/* argument sanity checking */
if (!arguments || arguments.length < 1)
alert("sprintf:ERROR: not enough arguments");

/* initialize processing queue */
var argumentnum = 0;
var done = "", todo = arguments[argumentnum++];

/* parse still to be done format string */
var m;
while (m = /^([^%]*)%(/d+$)?([#0 +'-]+)?(/*|/d+)?(/./*|/./d+)?([%diouxXfFcs])(.*)$/.exec(todo)) {
var pProlog = m[1],
pAccess = m[2],
pFlags = m[3],
pMinLength = m[4],
pPrecision = m[5],
pType = m[6],
pEpilog = m[7];

/* determine substitution */
var subst;
if (pType == '%')
/* special case: escaped percent character */
subst = '%';
else {
/* parse padding and justify aspects of flags */
var padWith = ' ';
var justifyRight = true;
if (pFlags) {
if (pFlags.indexOf('0') >= 0)
padWith = '0';
if (pFlags.indexOf('-') >= 0) {
padWith = ' ';
justifyRight = false;
}
}
else
pFlags = "";

/* determine minimum length */
var minLength = -1;
if (pMinLength) {
if (pMinLength == "*") {
var access = argumentnum++;
if (access >= arguments.length)
alert("sprintf:ERROR: not enough arguments");
minLength = arguments[access];
}
else
minLength = parseInt(pMinLength, 10);
}

/* determine precision */
var precision = -1;
if (pPrecision) {
if (pPrecision == ".*") {
var access = argumentnum++;
if (access >= arguments.length)
alert("sprintf:ERROR: not enough arguments");
precision = arguments[access];
}
else
precision = parseInt(pPrecision.substring(1), 10);
}

/* determine how to fetch argument */
var access = argumentnum++;
if (pAccess)
access = parseInt(pAccess.substring(0, pAccess.length - 1), 10);
if (access >= arguments.length)
alert("sprintf:ERROR: not enough arguments");

/* dispatch into expansions according to type */
var prefix = "";
switch (pType) {
case 'd':
case 'i':
subst = arguments[access];
if (typeof subst != "number")
subst = 0;
subst = subst.toString(10);
if (pFlags.indexOf('#') >= 0 && subst >= 0)
subst = "+" + subst;
if (pFlags.indexOf(' ') >= 0 && subst >= 0)
subst = " " + subst;
break;
case 'o':
subst = arguments[access];
if (typeof subst != "number")
subst = 0;
subst = subst.toString(8);
break;
case 'u':
subst = arguments[access];
if (typeof subst != "number")
subst = 0;
subst = Math.abs(subst);
subst = subst.toString(10);
break;
case 'x':
subst = arguments[access];
if (typeof subst != "number")
subst = 0;
subst = subst.toString(16).toLowerCase();
if (pFlags.indexOf('#') >= 0)
prefix = "0x";
break;
case 'X':
subst = arguments[access];
if (typeof subst != "number")
subst = 0;
subst = subst.toString(16).toUpperCase();
if (pFlags.indexOf('#') >= 0)
prefix = "0X";
break;
case 'f':
case 'F':
subst = arguments[access];
if (typeof subst != "number")
subst = 0.0;
subst = 0.0 + subst;
if (precision > -1) {
if (subst.toFixed)
subst = subst.toFixed(precision);
else {
subst = (Math.round(subst * Math.pow(10, precision)) / Math.pow(10, precision));
subst += "0000000000";
subst = subst.substr(0, subst.indexOf(".")+precision+1);
}
}
subst = '' + subst;
if (pFlags.indexOf("'") >= 0) {
var k = 0;
for (var i = (subst.length - 1) - 3; i >= 0; i -= 3) {
subst = subst.substring(0, i) + (k == 0 ? "." : ",") + subst.substring(i);
k = (k + 1) % 2;
}
}
break;
case 'c':
subst = arguments[access];
if (typeof subst != "number")
subst = 0;
subst = String.fromCharCode(subst);
break;
case 's':
subst = arguments[access];
if (precision > -1)
subst = subst.substr(0, precision);
if (typeof subst != "string")
subst = "";
break;
}

/* apply optional padding */
var padding = minLength - subst.toString().length - prefix.toString().length;
if (padding > 0) {
var arrTmp = new Array(padding + 1);
if (justifyRight)
subst = arrTmp.join(padWith) + subst;
else
subst = subst + arrTmp.join(padWith);
}

/* add optional prefix */
subst = prefix + subst;
}

/* update the processing queue */
done = done + pProlog + subst;
todo = pEpilog;
}
return (done + todo);
}
 

相关文章推荐

C语言atoi()函数:将字符串转换成int(整数)和sprintf和memset

atoi()函数 #include #include int main () { int i; char buffer[256]; printf ("Enter a n...

php中的sprintf()函数的format格式字符串

上次碰到的ASCII码问题,查看别人博客时,发现使用sprintf(),可以来输出。这个输出函数,以前也看了好多次,然而并未仔细看它的用途。这次就彻底查看手册,整明白,到底可以做什么。就有了如下的文档...

PHP字符串函数之 sscanf echo print sprintf vsprintf printf vprintf fprintf vfprintf

PHP字符串函数之 sscanf echo print sprintf vsprintf printf vprintf fprintf vfprintf标签:PHP字符函数 PHP字符串输入输出 ...

字符串拷贝函数 sprintf、strcpy 及 memcpy 的区别

这些函数的区别在于 实现功能 以及 操作对象 不同。 strcpy 函数操作的对象是 字符串,完成 从 源字符串 到 目的字符串 的 拷贝 功能。 snprintf 函数操作的对象 不限于...

HDU 5059 Help him(字符串 筛选数字 模拟)(atoi sprintf 函数)

两种方法:1、字符串直接模拟,2、运用atoll(),sprintf()函数

字符串 函数sprintf、strcpy 、strncpy及 memcpy , strftime,strcat

字符串 函数sprintf、strcpy 、strncpy及 memcpy , strftime,strcat (2012-02-06 16:56) 标签:  div  class  hi...

AIS中STM32程序,Sprintf函数,函数字符串形参

在一段字符串中间加上另外的字符串,并有相应的格式,组好的方法是使用sprintf格式化输出函数将其打印到另一个字符串中,最终的字符串就是自己想要的字符串。 sprintf函数的经典使用历程如下所示,...

C程序(scanf函数应用、字符串中取小数、两文件COPY、指针操作、stdout、stdin、stderr、sscanf、sprintf函数)

1.scanf函数相关应用 #include int main(  ) {        int i=0;        float f;  &#...

sprintf 字符串格式化

It may be old-fashioned, but I still find printf (and sprintf and _vsnprintf) incredibly useful, bot...
  • xjbzju
  • xjbzju
  • 2011-07-03 20:09
  • 3518

sprintf 字符串格式化

It may be old-fashioned, but I still find printf (and sprintf and _vsnprintf) incredibly useful, bot...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)