如何格式化数字以具有n个整数和小数位?
假设我有一个浮点数 x
,它有一个整数部分 a
和小数部分 b
,即 x = ab
。如何在 JavaScript 中格式化 x
使其最多包含 n
位数字,如下所示:
const n = 5
format(123.0) == '123'
format(123.01) == '123.01'
format(123.012) == '123.01'
format(0.0123) == '0.0123'
format(0.01234) == '0.0123'
Say I have a float x
that has a whole part a
and decimal part b
i.e. x = a.b
. How can I format x
in JavaScript such that it'll have at most n
digits, as shown below:
const n = 5
format(123.0) == '123'
format(123.01) == '123.01'
format(123.012) == '123.01'
format(0.0123) == '0.0123'
format(0.01234) == '0.0123'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基于最近删除的具有逻辑但实际上不起作用的答案,我想出了这个解决方案:
Based on a recently deleted answer that had the logic but didn't really work, I came up with this solution: