12051852 data like this is coming. I want to change it to 12.051.852. The number may be lower or higher. For example, I want to make the number 88312 88.312. How can I do Javasciprte? Thank you from now.
Asked
Active
Viewed 54 times
3 Answers
0
var a = 531123121
var myStr = a.toString().split("")
var myIndex = 0;
for(let i in a.toString().split("")){
var revIndex = a.toString().length - (parseInt(i)+1);
if((myIndex)==2 && revIndex!=0 && revIndex!=a.toString().length-1){
myStr.splice(revIndex,0,".")
myIndex = 0
}else myIndex+=1
}
console.log(myStr.join(""))
JaivBhup
- 742
- 2
- 7
0
You can do this very simply using the Intl API, and formatting the number to Spanish (es-ES).
Note: the language has come a long way since 2010 which is where of most of those answers in the duplicate come from.
const number = 12051852;
const number2 = 88312;
const number3 = 9;
const number4 = 12345678910;
const out = Intl.NumberFormat('es-ES').format(number);
const out2 = Intl.NumberFormat('es-ES').format(number2);
const out3 = Intl.NumberFormat('es-ES').format(number3);
const out4 = Intl.NumberFormat('es-ES').format(number4);
console.log(out);
console.log(out2);
console.log(out3);
console.log(out4);
Andy
- 53,323
- 11
- 64
- 89
-1
You can use a regular expression to group your numbers.
const rx = /(\d+?)(?=(\d{3})+(?!\d)|$)/g
const data = [
'12345678',
'12345',
'not_valid',
'1',
'12',
'123',
'1234',
'12345',
'123456',
'1234567891234567891234567891234567',
'12345678912345678912345678912345678',
'123456789123456789123456789123456789',
]
function parse(value) {
const m = value.match(rx)
let parsed
if (m) {
parsed = m.join('.')
}
return parsed
}
data.forEach(it => {
console.log(it, parse(it))
})
Steven Spungin
- 22,681
- 5
- 73
- 65