Ralph David Abernathy
Ralph David Abernathy

Reputation: 5518

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.

Upvotes: 3

Views: 4964

Answers (3)

Maxwell Farver
Maxwell Farver

Reputation: 1

try this:

var stringnumber = stringnumber.ToString();
var endresult = stringnumber.replace(".",",");

Upvotes: 0

MatthewG
MatthewG

Reputation: 9313

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('.', ',');

Upvotes: 5

Barry Kaye
Barry Kaye

Reputation: 7759

You cannot change the value of a const in javascript.

Upvotes: -1

Related Questions