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
3 Answers
Reset to default 5You 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
版权声明:本文标题:javascript - How to replace a decimal in a number with a string? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745533952a2662187.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论