I want to comma seperated value for my input box. For Example 2100000.90 will be 2,100,000.90. What I achieved is 2100000.90 to 2,100,000 from some Solution in Stack overflow
<div class="input">
<label for="salary">Salary</label>
<input class='inp_cont' id="salary" name="salary" placeholder="Enter your salary" required="" type="text">
</div>
And My Javascript is
document.getElementById('salary').addEventListener('input', event =>
event.target.value = (parseInt(event.target.value.replace(/[^\d]+/gi, '')) || 0).toLocaleString('en-US')
);
I want both comma separated and value after point.
Thanks in advance
You can try this
parseInt(number, 10).toLocaleString()
here is also the link from mozilla docs about Number.prototype.toLocaleString()
method. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
Your logic is defeated by its own.
Here is what you are currently doing:
what will happen when the user tries to input a decimal point? It will automatically be removed by the regex replace.
What you need to do is the following:
That will mess up if the user types more than one decimal point, but that can be detected and dealt with later
Therefor, it is essential to add the "dot" back if it is the last thing typed by the user.
document.getElementById('salary').addEventListener('input', event => { event.preventDefault(); // allow only digits and dots let text = event.target.value.replace(/[^\d\.]/gi, ''); // check if last character is a dot let lastCharIsAdot = text.substr(text.length - 1, 1) === "."; // try to check if input text is a valid number if (isNaN(text)) { // if not, then give feedback to the user event.target.classList.remove('valid'); event.target.classList.add('invalid'); } else { // if yes, then give positive feedback event.target.classList.remove('invalid'); event.target.classList.add('valid'); // format number event.target.value = Number(text).toLocaleString("en-US"); // this will remove the dot if it is the last thing input // therefor, we need to put it back if (lastCharIsAdot) event.target.value += "."; } });
.valid { background-color: lightgreen; color: darkgreen; }.invalid { background-color: pink; color: maroon; }
<div class="input"> <label for="salary">Salary</label> <input class='inp_cont' id="salary" name="salary" placeholder="Enter your salary" required="" type="text"> </div>
This function help you:
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
Output:
numberWithCommas(88888888.88)); // 88,888,888.88
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.