我有以下输入字段,其中将数字转换为美元货币格式。我有两个要解决的问题。 第一个是,当数字为数千时,我希望第一个数字用逗号分隔(例如:1,089.33)。第二个问题是,当我键入某些内容然后尝试完全删除输入内容时,它给了我0.00。我希望能够完全删除输入中的数字。 关于如何解决这两个问题的任何想法?
function formatAmountNoDecimals( number ) {
var rgx = /(\d+)(\d{3})/;
while( rgx.test( number ) ) {
number = number.replace( rgx, '$1' + '.' + '$2' );
}
return number;
}
function formatAmount( number ) {
// remove all the characters except the numeric values
number = number.replace( /[^0-9]/g, '' );
// set the default value
if( number.length == 0 ) number = "0.00";
else if( number.length == 1 ) number = "0.0" + number;
else if( number.length == 2 ) number = "0." + number;
else number = number.substring( 0, number.length - 2 ) + '.' + number.substring( number.length - 2, number.length );
// set the precision
number = new Number( number );
number = number.toFixed( 2 ); // only works with the "."
// change the splitter to ","
number = number.replace( /\./g, ',' );
// format the amount
x = number.split( ',' );
x1 = x[0];
x2 = x.length > 1 ? ',' + x[1] : '';
return formatAmountNoDecimals( x1 ) + x2;
}
$(function() {
$( '.amount' ).keyup( function() {
$( this ).val( formatAmount( $( this ).val() ) );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="tSaveext" class="amount" />
答案 0 :(得分:1)
尝试这样。
function formatAmountNoDecimals( number ) {
var rgx = /(\d+)(\d{3})/;
while( rgx.test( number ) ) {
number = number.replace( rgx, '$1' + ',' + '$2' );
}
return number;
}
function formatAmount( number ) {
// remove all the characters except the numeric values
number = number.replace( /[^0-9]/g, '' );
number = number.replace( /\./g, '' );
// set the default value
if( number.length == 0 ) number = "";
else if( number.length == 1 ) number = "0.0" + number;
else if( number.length == 2 ) number = "0." + number;
else number = number.substring( 0, number.length - 2 ) + '.' + number.substring( number.length - 2, number.length );
if(number){
// set the precision
number = new Number( number );
number = number.toFixed( 2 ); // only works with the "."
// change the splitter to ","
//console.log(number);
//number = number.replace( /\./g, ',' );
console.log(number);
// format the amount
x = number.split( ',' );
x1 = x[0];
x2 = x.length > 1 ? ',' + x[1] : '';
return formatAmountNoDecimals( x1 ) + x2;
} else {
return '';
}
}
$(function() {
$( '.amount' ).keyup( function() {
$( this ).val( formatAmount( $( this ).val() ) );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="tSaveext" class="amount" />