Adding Space Between Numbers
I'm trying to make a number input. I've made so my textbox only accepts numbers via this code: function isNumber(evt) { evt = (evt) ? evt : window.event; var charCode = (ev
Solution 1:
For integers use
functionnumberWithSpaces(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
}
For floating point numbers you can use
functionnumberWithSpaces(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ");
return parts.join(".");
}
This is a simple regex work. https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions << Find more about Regex here.
If you are not sure about whether the number would be integer or float, just use 2nd one...
Solution 2:
Easiest way:
1
var num = 1234567890,
result = num.toLocaleString() ;// result will equal to "1 234 567 890"
2
var num = 1234567.890,
result = num.toLocaleString() + num.toString().slice(num.toString().indexOf('.')) // will equal to 1 234 567.890
3
var num = 1234567.890123,
result = Number(num.toFixed(0)).toLocaleString() + '.' + Number(num.toString().slice(num.toString().indexOf('.')+1)).toLocaleString()
//will equal to 1 234 567.890 123
4
If you want ',' instead of ' ':
var num = 1234567.890123,
result = Number(num.toFixed(0)).toLocaleString().split(/\s/).join(',') + '.' + Number(num.toString().slice(num.toString().indexOf('.')+1)).toLocaleString()
//will equal to 1,234,567.890 123
If not working, set the parameter like: "toLocaleString('ru-RU')" parameter "en-EN", will split number by the ',' instead of ' '
Solution 3:
This function works well inside an input:
constformatAndVerifyNumericValue = (value, callback) => {
const reg = newRegExp('^[0-9]+$');
let newValue = value.replace(/\s/g, '');
if (reg.test(newValue)) {
newValue = newValue.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+.
(?!\d))/g, ' ');
returncallback(newValue);
}}
Post a Comment for "Adding Space Between Numbers"