动态重新格式化 JavaScript 中的输入以向数字添加逗号
我在输入数字时遇到问题。用户通常输入一个带有许多零的大数字, 而且经常会缺少一两个零,因为很难准确计数。
我认为 javascript 可以通过向用户显示他们输入的数字(用逗号格式化)来解决这个问题。
例如:
输入: | 1230000000000 |
结果:1,230,000,000,000
这是如何实现的?
I have an issue with number inputting. The user usually enters a large number with many zeros,
and often they are missing one or two zero as it is difficult to accurately count them.
I think javascript can work this out by showing the user the number they have inducted, formatted with commas.
eg:
input: | 1230000000000 |
Result: 1,230,000,000,000
How could this be accomplished?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
中使用以下函数
在 javascript示例
Use the following function in javascript
example
这是一个老问题,但仍然没有正确的答案,所以,这是我的动态解决方案,它需要相同的 addCommas 函数来重新格式化输出,但添加一个 keyup 事件来清理当前值(删除 ',' )并再次重新格式化新值价值。
在这里检查工作解决方案:
http://jsfiddle.net/darorck/371zrjet/
This is an old question but still without a correct answer so, this is my dynamic solution, it takes the same addCommas function to reformat the output but add a keyup event to clean the current value ( remove ',' ) and reformat again the new value.
Check the working solution here:
http://jsfiddle.net/darorck/371zrjet/
在现代浏览器中,您只需使用
toLocaleString()
即可实现此目的我知道我给出答案已经很晚了,但是我仍然发布了这个答案,因为这个问题出现在
How to add adynamic comma in number in javascript
的搜索结果中,所以我想我需要添加一个对于即将到来的开发人员来说更短、更好的答案。In modern browsers, you can simply achieve this with
toLocaleString()
I know I'm very late for giving the answer, But still, I post this answer because this question is coming in the search result of
How to add a dynamic comma in number in javascript
, So I thought I need to add an answer which is shorter and better for upcoming developers.