学习笔记9:JS将字符串转为会计专用的带,号的金额,并过滤不符合金额的格式
浏览量:3828
JS将字符串转为会计专用的带,号的金额,并过滤不符合金额的格式
<input type="text" id="txtprojectcost">
//把值按3个为一组加入,号,小数点内保留两位
为txtprojectcost增加keyup和blur方法
$("#txtprojectcost").keyup(function(){
if(isNaN(this.value.replaceAll(",",""))){
this.value = this.value.replaceAll(",","").replace(/[^\d.]/g, "");
为txtprojectcost增加keyup和blur方法
$("#txtprojectcost").keyup(function(){
if(isNaN(this.value.replaceAll(",",""))){
this.value = this.value.replaceAll(",","").replace(/[^\d.]/g, "");
this.value=this.value.replaceAll(",","").replace(/^\./g, "");//首位不能为.
this.value=this.value.replaceAll(",","").replace(/^00/g, "");//首两位不能为00
}
}).blur(function(){
jiSuan(this);
});
this.value=this.value.replaceAll(",","").replace(/^00/g, "");//首两位不能为00
}
}).blur(function(){
jiSuan(this);
});
function jiSuan(obj)
{
var newStr = "";
var count = 0;
{
var newStr = "";
var count = 0;
obj.value=obj.value.replaceAll(",","");
if(obj.value=="") return;
if(obj.value.indexOf(".")==-1)
{
for(var i=obj.value.length-1;i>=0;i--)
{
if(count % 3 == 0 && count != 0)
{
newStr = obj.value.charAt(i) + "," + newStr;
}
else
{
newStr = obj.value.charAt(i) + newStr;
}
count++;
}
obj.value = newStr + ".00";
}
else
{
for(var i=obj.value.indexOf(".")-1;i>=0;i--)
{
if(count % 3 == 0 && count != 0)
{
newStr = obj.value.charAt(i) + "," + newStr;
}
else
{
newStr = obj.value.charAt(i) + newStr;
}
count++;
}
if(obj.value=="") return;
if(obj.value.indexOf(".")==-1)
{
for(var i=obj.value.length-1;i>=0;i--)
{
if(count % 3 == 0 && count != 0)
{
newStr = obj.value.charAt(i) + "," + newStr;
}
else
{
newStr = obj.value.charAt(i) + newStr;
}
count++;
}
obj.value = newStr + ".00";
}
else
{
for(var i=obj.value.indexOf(".")-1;i>=0;i--)
{
if(count % 3 == 0 && count != 0)
{
newStr = obj.value.charAt(i) + "," + newStr;
}
else
{
newStr = obj.value.charAt(i) + newStr;
}
count++;
}
obj.value = newStr + (obj.value + "00").substr((obj.value + "00").indexOf("."),3);
}
}
}
由于给值加入逗号后正则判断会认为值不符合,所以需要替换到字符串内所有的,号,AFindText要替换掉得字符,ARepText 替换为
String.prototype.replaceAll = stringReplaceAll;
function stringReplaceAll(AFindText,ARepText){
var st='/'+AFindText+"/gi";
return this.replace(eval("/"+AFindText+"/ig"),ARepText);
}
由于给值加入逗号后正则判断会认为值不符合,所以需要替换到字符串内所有的,号,AFindText要替换掉得字符,ARepText 替换为
String.prototype.replaceAll = stringReplaceAll;
function stringReplaceAll(AFindText,ARepText){
var st='/'+AFindText+"/gi";
return this.replace(eval("/"+AFindText+"/ig"),ARepText);
}