使用两位小数格式化数字,用空格而不是 0 填充
我正在寻找一种有效的方法来返回 JavaScript 中浮点数的字符串格式,其格式如下:
#,##0
但如果没有小数,我希望使用尾随“空格”而不是零,以便使数字对齐以下方式(基本上使小数点全部对齐)。如果它有尾部填充,我可以简单地向右对齐以使它们正确对齐。
10.12
101.3
10
谢谢,
I am looking for an efficient way to return a string formatt of a float in javascript that is formatted in the following way:
#,##0
But I want to have trailing "spaces" instead of zero's if there is no decimals in order to have the numbers aligned in the following fashion (basically so that the decimal points all line up). If it has trailing padding, I can simply align to the right to have them align correctly.
10.12
101.3
10
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
应该很好地满足您的需求。
其中:
返回:(
为了可见性,下划线作为空格)
Should suite your needs nicely.
Where:
Returns:
(Underscores as spaces for sake of visibility)
Javascript 有点生疏,但我想你可以从中得到启发。
Little rusty with Javascript but I think you can get the idea from this.
是否添加逗号并正确设置小数部分。
带负数的版本
Does add commas and set the decimal part correctly.
Version with negative numbers
我首先使用尾随零格式化字符串。然后您应该能够应用正则表达式来检查字符串末尾是否有 0 字符串,并将它们替换为空格。
I would start with formatting the string with the trailing zeros. Then you should be able to apply a Regex to check for a string of 0's at the end of the string, and replace them with spaces.
可能有一种更简单的方法可以使用正则表达式来做到这一点,但这是我的快速实现:
There's probably an easier way to do this with regular expressions, but here's my quick implementation: