I have the following input field where I'm converting a number to a dollar currency format. I have two issues that I'm trying to solve. The first one is that when the number is in the thousands I would like the first digit to split with a comma (example: 1,089.33). And the second issue is that when I type something and then try to entirely delete whatever is inside the input it gives me a 0,00. I would like to be able to delete the number entirely inside the input. Any ideas on how to fix both of these issues?
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" />