-3

How to make a format number like below in javascript, i try workit with some regex, but it's not working.

99.999.999.9.999.999

Riantori
  • 317
  • 1
  • 4
  • 14

2 Answers2

1
(9999999999999).toString().split("").reverse().map((el,i)=>(i+1)%3==0?"."+el:el).reverse().join("");

Make a string array out of it, then start from behind and add a point after each third element, then create a String out of that.

http://jsbin.com/lepecoyedo/edit?console

Alternatively, with fixed , positions:

var num=(9999999999999).toString().split("").reverse();
[3,6,7].forEach((i,o)=>num.splice(o+i,0,"."));//positions 3,6,8 (or others) from behind
num=num.reverse().join("");

http://jsbin.com/xahopuhira/edit?console

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Hi Jonas, thanks for your help but the format should be exactly 99.999.999.9.999.999 , and you code result is 9.999.999.999.999, i have no idea how to split the number – Riantori May 13 '17 at 18:31
1

You could use a regular expression with positive lookahead for a special length to the end of the string.

var regex = /(?=(.{13}|.{10}|.{7}|.{6}|.{3})$)/g,
    value = '999999999999999',
    result = value.replace(regex, '.');
    
console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392