Ruby 中的 Sprintf
这是一个快速的问题。我正在写:
puts "%.3f %.4f %.5f" % [3.998877, 3.998877, 3.998877]
并得到以下输出:
3.999 3.9989 3.99888
sprintf 只是对数字进行四舍五入。如何限制舍入?
Sort of a quick question. I'm writing:
puts "%.3f %.4f %.5f" % [3.998877, 3.998877, 3.998877]
and get the following output:
3.999 3.9989 3.99888
sprintf simply rounds the numbers. How do I restrict that rounding?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能需要将数字截断到您想要的精度。
you will probably need to truncate the numbers to the accuracy that you want.
要按原样获取数字,您应该将它们存储为字符串。一旦将它们表示为浮点数,您就会丢失有关内置精度的信息。
To get the numbers 'as is', you should store them as strings. As soon as you represent them as floats you lose information about the amount of built-in precision.