how to format a string or number to thousand group in typescript

489 views Asked by At

My function just want to format a number or string from 'xxxxx.xx' to 'xx,xxx.xx' or xxxxx.xx to 'xx,xxx.xx'

function format(text: number | string): string {
  return `${+text.toLocaleString()}`;
}
console.log(format(123456)); #123,456
console.log(format(123456.78)); #123,456.78
console.log(format('123456')); #123,456
console.log(format('123456.78')); #123,456.78
=> 
NaN
NaN
123456
123456.78
1

There are 1 answers

0
derkoe On

This works:

function format(text: number | string): string {
  return Number(text).toLocaleString();
}

Number converts a string to a number, see Number at MDN.