Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sprintf in Ruby

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?

like image 969
gmile Avatar asked Mar 01 '23 05:03

gmile


2 Answers

>> 3.998877.to_s[/^\d+\.\d{3}/].to_f
=> 3.998
>> 3.998877.to_s[/^\d+\.\d{4}/].to_f
=> 3.9988
like image 169
cldwalker Avatar answered Mar 05 '23 20:03

cldwalker


>> def truncN f, digits
>>    t = 10.0 ** digits
>>    "%.#{digits}f" % ((f * t).truncate / t)
>> end
=> nil
>> n
=> 1.11181111
>> "%.3f" % n
=> "1.112"
>> truncN n, 3
=> "1.111"
like image 41
DigitalRoss Avatar answered Mar 05 '23 22:03

DigitalRoss