我一直在尝试将输入视为货币并使用逗号。我的输出显示带小数的货币,但它缺少逗号。我试图让这两件事情一起工作,但我一直遇到错误。任何帮助表示赞赏!!
function calculate(){
var savingsVal = ($('#savingsVal').val());
var totalSavings = 0;
if (filterValues(savingsVal)) {
totalSavings = savingsVal * 0.15;
}
$('#totalSavings').val('$' + totalSavings);
}
function filterValues(eVal){
if (eVal.length == 0)
{
$('.errorMessage').text('Insert value');
$('.equipValCont').addClass('has-error');
return false;
}
else if(!$.isNumeric(eVal)){
$('.errorMessage').text('Please, enter only numbers');
$('.equipValCont').addClass('has-error');
return false;
} else{
$('.equipValCont').removeClass('has-error');
return true;
}
}
$('#calculator').submit(function(e){
e.preventDefault();
calculate();
});
答案 0 :(得分:0)
答案 1 :(得分:0)
要进行验证,请使用正则表达式验证您的值,而不是检查else if(!$.isNumeric(eVal)){
。您必须将“,”视为有效,因为您的货币将允许“,”。以下作为样本
var currencyStr= "1,123.20";
if (/^\d{0,4}(\.\d{0,2})?$/.test(currencyStr))
alert("currency is valid");
答案 2 :(得分:0)
你应该改变
if (/^\d{0,4}(\.\d{0,2})?$/.test(currencyStr))
alert("currency is valid");
到
if (/^(\d{0,3})(,\d{0,3})*(\.\d{0,2})?$/.test(currencyStr))
alert("currency is valid");
我希望这有助于你
<强>更新强>
如果您想要输出正确的逗号,请尝试以下操作:
function formatStr( str ) {
str = str.replace( /,/g, "" );
var result = str.match( /^([^\.]+)(\.\d{0,2})?$/ ),
newStr = "",
integerStr = result[1] ? result[1] : "",
floatStr = result[2] ? result[2] : "",
j = 0;
for ( var i = integerStr.length - 1; i >= 0; i-- ) {
if ( j == 3 ) {
newStr = integerStr[i] + "," + newStr;
j = 1;
}
else {
newStr = integerStr[i] + newStr;
j++;
}
}
newStr = newStr + floatStr;
console.log( newStr );
return newStr;
}
formatStr( "12.34" );
formatStr( "123" );
formatStr( "1234.56" );
formatStr( "12345.6" );
&#13;