Search code examples
javascriptstringreplacenumbersdecimal-point

How to replace a decimal in a number with a string?


How can I replace a decimal in a number with a string? For example, if I have a number 12.12, how can I take the decimal in that number and replace it with a comma (,) so that the output would be 12,12?

I tried this, but my app crashes because of it:

let number = 12.12

number.replace(/./g, ',');

Thanks.


Solution

  • You cannot use replace on a number, but you can use it on a string. Convert your number to a string, and then call replace. Also, the period (.) character has special meaning in regular expressions. But you can just pass a plain string to replace.

    const numberWithCommas = number.toString().replace('.', ',');