Right now I have the following code implemented:
$(document).ready(function() {
let maximumFractionDigits = 2;
var valueInput = $("#exampleInput");
const formatNumber = (value) => {
return parseFloat(value.replace(/,/g,'')).toLocaleString('en-US', { maximumFractionDigits });
}
valueInput.on('input', function() {
if (!this.value || (maximumFractionDigits && this.value.endsWith('.'))) {
return
}
$(this).val(formatNumber(this.value));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="exampleInput" class="form-control" aria-label="Grant Amount" type="text" placeholder="0" name="price" required="">
It works fine and does what I want: when the user enters more than 3 digits the thousand comma separator is added and two decimal places are allowed (USD format).
However, if the user enters some number in another charset, for example with a Japanese keyboard, or any unexpected char the following message appears:
'NaN'
Expected outcome:
If the user enters an invalid character, it should not appear in the input (I want to avoid NaN message), for example if I enter 'a' nothing will appear in the input.
What I've tried:
Somehow I tried to use the isNaN function but my approach is definitely wrong.
const formatNumber = (value) => {
if (isNaN(value)){
return 0;
} else{
return parseFloat(value.replace(/,/g,'')).toLocaleString('en-US', { maximumFractionDigits });
}
}
If anyone could help me I would really appreciate it