Javascript 与 C# 一样格式化数字
我的号码目前为 1,657,108,700,并且还在不断增长。不过我希望它显示为 1,657,108k
javascript 或 html 是否有内置函数可以执行此操作?
该值通过 javascript 设置为 html 中的 span 字段。
[编辑]
从评论中我得到了我的方法:
var start = '1,657,108,700';
start = (start / 1000).toFixed(0);
var finish = '';
while (start.length > 3)
{
finish = ','.concat(start.substring(start.length - 3, 3), finish);
start = start.substring(0, start.length - 3);
};
finish = start + finish + "k";
return finish;
但是这返回 1,65,7k 而不是 1,657,108k..有人知道为什么吗?
I have a number which currently is 1,657,108,700 and growing. However I wish for it to show as
1,657,108k
Does javascript or html have a build in function to do this?
The value is being set throu javascript to a span field in html.
[edit]
From the comment I got my method as far as:
var start = '1,657,108,700';
start = (start / 1000).toFixed(0);
var finish = '';
while (start.length > 3)
{
finish = ','.concat(start.substring(start.length - 3, 3), finish);
start = start.substring(0, start.length - 3);
};
finish = start + finish + "k";
return finish;
however this returns 1,65,7k instead of 1,657,108k.. anyone know why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
视情况将上面的变成函数或者不变成函数。我不知道有哪个函数可以做到这一点,也不知道有一种方法可以满足非英语版本的“k”(假设有一些),但至少应该采用
toLocaleString()
处理千分号问题中的逗号与句号。更新:我发布了上面的内容,但没有对其进行测试;当我尝试时,我发现 toLocaleString() 将 1234 格式化为 1,234.00。我曾想过通过使用正则表达式替换来删除尾随零来修复它,当然我无法确定 toLocaleString() 将使用哪个字符作为小数点,所以这是行不通的。我想您可以编写一些在“控制”数字(例如 1.1)上使用 toLocaleString() 的代码,以在运行时查看它用于小数的字符。
UPDATE 2 对于您更新的问题,手动插入逗号,我是这样做的:
Turn the above into a function or not as appropriate. I'm not aware of a single function to do this, or of a way to cater for non-English versions of "k" (assuming there are some), but at least
toLocaleString()
should take care of the comma versus fullstop for thousands issue.UPDATE: I posted the above without testing it; when I tried it out I found toLocaleString() formatted 1234 as 1,234.00. I had thought of fixing it by using a regex replace to remove trailing zeros except of course I can't be sure what character toLocaleString() is going to use for the decimal point, so that won't work. I guess you could write some code that uses toLocaleString() on a "control" number (e.g., 1.1) to see at runtime what character it uses for the decimal.
UPDATE 2 for your updated question, inserting the commas manually, I did it like this: