数字格式转换、日期格式转换

2018/12/18 16:37
阅读数 8

/**
* 公用javascript库
*/

/**
* 将数值四舍五入(保留2位小数)后格式化成金额形式
*
* @param num
* 数值(Number或者String)
* @return 金额格式的字符串,如'1,234,567.45'
* @type String
*/
function formatCurrency(num) {
if (!num) return '0.00';
num = num.toString().replace(/\$|\,/g, '');
if (isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num * 100 + 0.50000000001);
cents = num % 100;
num = Math.floor(num / 100).toString();
if (cents < 10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
num = num.substring(0, num.length - (4 * i + 3)) + ','
+ num.substring(num.length - (4 * i + 3));
return (((sign) ? '' : '-') + num + '.' + cents);
}

/**
* (保留2位小数)后格式化成金额形式
*
* @param num
* 数值(Number或者String)
* @return 金额格式的字符串,如'1,234,567.4567'
* @type String
*/
function formatCurrency2(num) {
if (!num) return '0.00';
num = num.toString().replace(/\$|\,/g, '');
if (isNaN(num))
num = "0.00";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num * 10000);
cents = num % 10000;
num = Math.floor(num / 10000).toString();
if (cents < 10){
cents = "000" + cents;
}else if(cents < 100){
cents = "00" + cents;
}else if(cents < 1000){
cents = "0" + cents;
}
cents = cents.toString();
cents = cents.substring(0,2);
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
num = num.substring(0, num.length - (4 * i + 3)) + ','
+ num.substring(num.length - (4 * i + 3));
return (((sign) ? '' : '-') + num + '.' + cents);
}

/**
* 将数值四舍五入(保留4位小数)后格式化成金额形式
*
* @param num
* 数值(Number或者String)
* @return 金额格式的字符串,如'1,234,567.4567'
* @type String
*/
function formatCurrency3(num) {
if (!num) return '0.0000';
// num = num.toString().replace(/\$|\,/g, '');
console.log("==="+num);
if (isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num * 10000 + 0.50000000001);
cents = num % 10000;
console.log(cents+"==="+num);
num = Math.floor(num / 10000).toString();
if (cents < 10){
cents = "000" + cents;
}else if(cents < 100){
cents = "00" + cents;
}else if(cents < 1000){
cents = "0" + cents;
}
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
num = num.substring(0, num.length - (4 * i + 3)) + ','
+ num.substring(num.length - (4 * i + 3));
return (((sign) ? '' : '-') + num + '.' + cents);
}

/**
* 将数值四舍五入(保留1位小数)后格式化成金额形式
*
* @param num
* 数值(Number或者String)
* @return 金额格式的字符串,如'1,234,567.4'
* @type String
*/
function formatCurrencyTenThou(num) {
num = num.toString().replace(/\$|\,/g, '');
if (isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num * 10 + 0.50000000001);
cents = num % 10;
num = Math.floor(num / 10).toString();
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
num = num.substring(0, num.length - (4 * i + 3)) + ','
+ num.substring(num.length - (4 * i + 3));
return (((sign) ? '' : '-') + num + '.' + cents);
}

//对Date的扩展,将 Date 转化为指定格式的String
//月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
//年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
//例子:
//(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
//(new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function(fmt)
{ //author: meizz
var o = {
"M+" : this.getMonth()+1, //月份
"d+" : this.getDate(), //日
"h+" : this.getHours(), //小时
"m+" : this.getMinutes(), //分
"s+" : this.getSeconds(), //秒
"q+" : Math.floor((this.getMonth()+3)/3), //季度
"S" : this.getMilliseconds() //毫秒
};
if(/(y+)/.test(fmt))
fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
for(var k in o)
if(new RegExp("("+ k +")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
return fmt;
}

/**
* 日期格式化
* @returns {___anonymous_DateFormat}
*/
DateFormat = (function() {
var SIGN_REGEXP = /([yMdhsm])(\1*)/g;
var DEFAULT_PATTERN = 'yyyy-MM-dd';

function padding(s, len) {
var len = len - (s + '').length;
for (var i = 0; i < len; i++) {
s = '0' + s;
}
return s;
}
;

return ({
format : function(date, pattern) {
pattern = pattern || DEFAULT_PATTERN;
return pattern.replace(SIGN_REGEXP, function($0) {
switch ($0.charAt(0)) {
case 'y':
return padding(date.getFullYear(), $0.length);
case 'M':
return padding(date.getMonth() + 1, $0.length);
case 'd':
return padding(date.getDate(), $0.length);
case 'w':
return date.getDay() + 1;
case 'h':
return padding(date.getHours(), $0.length);
case 'm':
return padding(date.getMinutes(), $0.length);
case 's':
return padding(date.getSeconds(), $0.length);
}
});
},
parse : function(dateString, pattern) {
var matchs1 = pattern.match(SIGN_REGEXP);
var matchs2 = dateString.match(/(\d)+/g);
if (matchs1.length == matchs2.length) {
var _date = new Date(1970, 0, 1);
for (var i = 0; i < matchs1.length; i++) {
var _int = parseInt(matchs2[i]);
var sign = matchs1[i];
switch (sign.charAt(0)) {
case 'y':
_date.setFullYear(_int);
break;
case 'M':
_date.setMonth(_int - 1);
break;
case 'd':
_date.setDate(_int);
break;
case 'h':
_date.setHours(_int);
break;
case 'm':
_date.setMinutes(_int);
break;
case 's':
_date.setSeconds(_int);
break;
}
}
return _date;
}
return null;
}
});
})();


//数字转换为中文大写
function convertCurrency(currencyDigits) {
// Constants:
var MAXIMUM_NUMBER = 99999999999.99;
// Predefine the radix characters and currency symbols for output:
var CN_ZERO = "零";
var CN_ONE = "壹";
var CN_TWO = "贰";
var CN_THREE = "叁";
var CN_FOUR = "肆";
var CN_FIVE = "伍";
var CN_SIX = "陆";
var CN_SEVEN = "柒";
var CN_EIGHT = "捌";
var CN_NINE = "玖";
var CN_TEN = "拾";
var CN_HUNDRED = "佰";
var CN_THOUSAND = "仟";
var CN_TEN_THOUSAND = "万";
var CN_HUNDRED_MILLION = "亿";
// var CN_SYMBOL = "¥:";
var CN_SYMBOL = "";
var CN_DOLLAR = "元";
var CN_TEN_CENT = "角";
var CN_CENT = "分";
var CN_INTEGER = "整";

// Variables:
var integral; // Represent integral part of digit number.
var decimal; // Represent decimal part of digit number.
var outputCharacters; // The output result.
var parts;
var digits, radices, bigRadices, decimals;
var zeroCount;
var i, p, d;
var quotient, modulus;

// Validate input string:
currencyDigits = currencyDigits.toString();
if (currencyDigits == "") {
alert("请输入要转换的数字!");
return "";
}
if (currencyDigits.match(/[^,.\d]/) != null) {
alert("数字中含有非法字符!");
return "";
}
if ((currencyDigits)
.match(/^((\d{1,3}(,\d{3})*(.((\d{3},)*\d{1,3}))?)|(\d+(.\d+)?))$/) == null) {
alert("错误的数字格式!");
return "";
}

// Normalize the format of input digits:
currencyDigits = currencyDigits.replace(/,/g, ""); // Remove comma
// delimiters.
currencyDigits = currencyDigits.replace(/^0+/, ""); // Trim zeros at the
// beginning.
// Assert the number is not greater than the maximum number.
if (Number(currencyDigits) > MAXIMUM_NUMBER) {
alert("超出转换最大范围!");
return "";
}

// Process the coversion from currency digits to characters:
// Separate integral and decimal parts before processing coversion:
parts = currencyDigits.split(".");
if (parts.length > 1) {
integral = parts[0];
decimal = parts[1];
// Cut down redundant decimal digits that are after the second.
decimal = decimal.substr(0, 2);
} else {
integral = parts[0];
decimal = "";
}
// Prepare the characters corresponding to the digits:
digits = new Array(CN_ZERO, CN_ONE, CN_TWO, CN_THREE, CN_FOUR, CN_FIVE,
CN_SIX, CN_SEVEN, CN_EIGHT, CN_NINE);
radices = new Array("", CN_TEN, CN_HUNDRED, CN_THOUSAND);
bigRadices = new Array("", CN_TEN_THOUSAND, CN_HUNDRED_MILLION);
decimals = new Array(CN_TEN_CENT, CN_CENT);
// Start processing:
outputCharacters = "";
// Process integral part if it is larger than 0:
if (Number(integral) > 0) {
zeroCount = 0;
for (i = 0; i < integral.length; i++) {
p = integral.length - i - 1;
d = integral.substr(i, 1);
quotient = p / 4;
modulus = p % 4;
if (d == "0") {
zeroCount++;
} else {
if (zeroCount > 0) {
outputCharacters += digits[0];
}
zeroCount = 0;
outputCharacters += digits[Number(d)] + radices[modulus];
}
if (modulus == 0 && zeroCount < 4) {
outputCharacters += bigRadices[quotient];
}
}
outputCharacters += CN_DOLLAR;
}
// Process decimal part if there is:
if (decimal != "") {
for (i = 0; i < decimal.length; i++) {
d = decimal.substr(i, 1);
if (d != "0") {
outputCharacters += digits[Number(d)] + decimals;
}
}
}
// Confirm and return the final output string:
if (outputCharacters == "") {
outputCharacters = CN_ZERO + CN_DOLLAR;
}
if (decimal == "") {
outputCharacters += CN_INTEGER;
}
outputCharacters = CN_SYMBOL + outputCharacters;
return outputCharacters;
}

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部