Search code examples
stringtypescriptcastinglocale

Provide Decimal Point Number to .toLocaleString() in TypeScript


I am trying to form a number having a decimal separator from a string in order to be able to apply .toLocaleString() method , which cannot be applied on strings.

const initialString = 122; //number
const decimalStr = initialString.toFixed(initialString); //string
const formattedStr = decimalStr.toLocaleString('de-DE');//error,decimalStr is a string

If any conversion is to be applied to the decimalStr, the decimal digits would be lost ( i.e. decimalStr = +decimalStr or decimalStr = Number(decimalStr). => problem, need to keep decimal digits.

How can i keep the decimal points and make the .toLocaleString() see calling value as a number?


Solution

  • The Number.toLocaleString method accepts a second argument called options. You can use this argument to control the number of fraction digits. Therefore, your call would be:

    const initialNumber = 122; 
    const formattedStr = initialNumber.toLocaleString('de-DE', {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    });
    

    For more details check here.

    Also, notice that both toFixed and the maximumFractionDigits have limits: 100 and 20, respectively. So the example you provide fails on the second line.