最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to replace a decimal in a number with a string? - Stack Overflow

programmeradmin1浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论