2012-05-17 40 views
0

嘿傢伙應該是一個容易的...我有一些JavaScript將輸入值轉換爲貨幣值。問題是,如果我嘗試在0.5到鍵入它會失敗繼承人是我的代碼:JavaScript isCurrency()失敗

function handleCurrency(formName,fieldName) 
{ 
    var enteredValue = document.forms[formName].elements[fieldName].value; 

    if (enteredValue.isCurrency()) 
    { 
     alert("This is currency " + enteredValue) 
     // Put the nicely formatted back into the text box. 
     document.forms[formName].elements[fieldName].value = enteredValue.toCurrency(); 
    } 
} 

的jsp:

<td><input type="text" name="replacementCost" onchange="handleCurrency('NsnAdd','replacementCost')" value="<ctl:currencyFormat currency='${form.replacementCost}'/>" onkeypress="javascript:return noenter();" <c:if test="${!lock.locked}">disabled="disabled"</c:if> /></td> 

我怎樣才能讓這個.5允許也被格式化?

自定義的javascript:

var patternWithCommas = new RegExp("^\\s*\\$?-?(\\d{1,3}){1}(,\\d{3}){0,}(\\.\\d{1,2})?\\s*$"); 
var patternWithoutCommas = new RegExp("^\\s*\\$?-?\\d+(\\.\\d{1,2})?\\s*$"); 

function stringIsCurrency() 
{ 
if (patternWithoutCommas.test(this)) 
{ 
    return true; 
} 
else if (patternWithCommas.test(this)) 
{ 
    return true; 
} 
return false; 
} 

function stringToCurrency() 
{ 
if (this == '') return this; 

var str = this.replace(/[$,]+/g,''); 

sign = (str == (str = Math.abs(str))); 
str = Math.floor(str*100+0.50000000001); 
cents = str%100; 
str = Math.floor(str/100).toString(); 

if (cents<10) cents = "0" + cents; 

for (var i = 0; i < Math.floor((str.length-(1+i))/3); i++) 
{ 
    str = str.substring(0,str.length-(4*i+3))+','+ 
      str.substring(str.length-(4*i+3)); 
} 

str = '$' + ((sign)?'':'-') + str + '.' + cents; 

return str; 
} 

String.prototype.isCurrency = stringIsCurrency; 
String.prototype.toCurrency = stringToCurrency; 

基本上它需要允許1.5到不只是0.5

這需要更新:

var patternWithCommas = new RegExp("^\\s*\\$?-?(\\d{1,3}){1}(,\\d{3}){0,}(\\.\\d{1,2})?\\s*$"); 
+4

什麼是'isCurrency()'? –

+0

我的壞...我們有它定製 –

回答

1

您還沒有表現出你的代碼isCurrency

這是我會怎麼做:

function isCurrency(val) 
{ 
    return /^\$?(?:\d[\d,]*)?(?:.\d\d?)?$/.test(val); 
} 

看到它在這裏的行動:http://regexr.com?3103a


現在您提供您的代碼,這是我提出的解決方案。

雖然有很多事情我會做不同,
爲了保持你的代碼的精神,只是改變這一點:

var patternWithCommas = new RegExp("^\\s*\\$?-?(\\d{1,3}){1}(,\\d{3}){0,}(\\.\\d{1,2})?\\s*$"); 
var patternWithoutCommas = new RegExp("^\\s*\\$?-?\\d+(\\.\\d{1,2})?\\s*$"); 

這樣:

var patternWithCommas = /^\s*\$?-?((\d{1,3}){1}(,\d{3})?)?(\.\d{1,2})?\s*$/; 
var patternWithoutCommas = /^\s*\$?-?(\d+)?(\.\d{1,2})?\s*$/; 

這將使美元數量可選。

+0

我已添加isCurrency –

+0

@DocHoliday - 我發佈了一些更多的代碼給你。希望這可以幫助。 –

+0

嘿,真的幫助....非常感謝....我似乎很容易被正則表達式困惑 –