javascript相关格式化
1.格式化金钱(正数)
function formatMoney(
str) {
var
str = String(
str);
var newStr =
"";
var
count =
0;
if (
str.indexOf(
".") == -
1) {
for (var i =
str.length -
1; i >=
0; i--) {
if (
count %
3 ==
0 &&
count !=
0) {
newStr =
str.charAt(i) +
"," + newStr;
}
else {
newStr =
str.charAt(i) + newStr;
}
count++;
}
str = newStr +
".00";
}
else {
for (var i =
str.indexOf(
".") -
1; i >=
0; i--) {
if (
count %
3 ==
0 &&
count !=
0) {
newStr =
str.charAt(i) +
"," + newStr;
}
else {
newStr =
str.charAt(i) + newStr;
}
count++;
}
str = newStr + (
str +
"00").substr((
str +
"00").indexOf(
"."),
3);
}
return str;
}
2.格式化金钱(包含负数)
/**
* 将数值四舍五入(保留2位小数)后格式化成金额形式
* 包含对于负数的操作
* @param num 数值(Number或者String)
* @return 金额格式的字符串,如'1,234,567.45'
* @type String
*/
function formatMoneyNew(num) {
var result = num;
if (num <
0){
num =
0 - num;
}
if (/[^
0-
9\.]/.test(num)){
return "0.00";
}
if (num ==
null || num ==
"null" || num ==
""||isNaN(num)){
return "0.00";
}
num =
new Number(num).toFixed(
2);
num = num.toString().replace(/^(\d*)$/,
"$1.");
num = (num +
"00").replace(/(\d*\.\d\d)\d*/,
"$1");
num = num.replace(
".",
",");
var re = /(\d)(\d{
3},)/;
while (re.test(num)){
num = num.replace(re,
"$1,$2");
}
num = num.replace(/,(\d\d)$/,
".$1");
if (result <
0){
result =
"-" + num ;
}
else {
result = num;
}
return result;
}
3.格式化日期
/**
* 格式化日期 js把字符串(yyyymmdd)转换成日期格式(yyyy-mm-dd)
*/
function formatDate(str){
if(str !=
null && str != undefined && str !=
'' && str !=
'null'){
return str.replace(/^(\d{
4})(\d{
2})(\d{
2})$/,
"$1-$2-$3");
}
else {
return "";
}
}
4.格式化数据
/**
* 格式化数据 字符串内容为空转化成""
*/
function formatValue(str){
if(str !=
null && str != undefined && str !=
'' && str !=
'null'){
return str;
}
else {
return "";
}
}