admin管理员组

文章数量:1429490

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

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

Share Improve this question edited Jan 26, 2018 at 19:31 Ralph David Abernathy asked Jan 26, 2018 at 19:24 Ralph David AbernathyRalph David Abernathy 5,51813 gold badges56 silver badges87 bronze badges 2
  • Are you trying to do this in order to localize the output? If so, mentioning that in the question may alter the answers you get and provide solutions that will allow some folks to see periods and others to see mas depending on how their puters are configured. – Jason Aller Commented Jan 26, 2018 at 20:37
  • I'm using this to write a utility that replaces the ining decimal from the backend with whatever thousands separator is associated with the current locale. – Ralph David Abernathy Commented Jan 27, 2018 at 21:26
Add a ment  | 

3 Answers 3

Reset to default 5

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

try this:

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

You cannot change the value of a const in javascript.

本文标签: javascriptHow to replace a decimal in a number with a stringStack Overflow