开发者

how to print floats with 6 digits only - Ruby

Okay.. I have these float numbers in a ruby array :-) 12.321912389 122.438783 345.23242444 89.37827383

I want to convert these numbers to 6 digits numbers without l开发者_StackOverflow中文版osing float property. something like :-) 12.3219 122.438 345.232 89.3782

Which function can help me? sorry if this question is very naive to you :-)


You can play with sprintf "g" format, what you need is 6 significant digits:

(0..6).map{|i| '%.6g' % (10.0**i / 3)}
=> ["0.333333", "3.33333", "33.3333", "333.333", "3333.33", "33333.3", "333333"]


This is very stupid (and slow), but it works (assuming numbers contain decimal point):

numbers = [12.321912389, 122.438783, 345.23242444, 89.37827383]
numbers.map! { |num| num.to_s[0..6].to_f }
p numbers    #=> [12.3219, 122.438, 345.232, 89.3782]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜