Forum: Ruby printing float to string with decimal rounding

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Josselin (Guest)
on 2007-05-23 18:27
(Received via mailing list)
I am trying to print a float result in a string but I can get it right

I get float numbers like :
distance =  0.2568915421 , 1.2568910001,  20.3256941254   (8 decimals)

I wrote
    d = (distance.*1000).round/1000.0     # to get something like  0.257
    return "(- de 500m)" if d < 0.500
    return "( - de 1km)" if d < 1.0
    return "(env. " + d.to_s + " km)"

if d > 1.0   i print   "env. 1.257 km"
I'd like to print "env. 1.2 km"  shoudl I round it again ? or is there
any DRY solution ?

thanks

joss
Farrel L. (Guest)
on 2007-05-23 18:35
(Received via mailing list)
On 23/05/07, Josselin <removed_email_address@domain.invalid> wrote:
>
> if d > 1.0   i print   "env. 1.257 km"
> I'd like to print "env. 1.2 km"  shoudl I round it again ? or is there
> any DRY solution ?
>
> thanks
>
> joss

Kernel#format

Farrel
Robert K. (Guest)
on 2007-05-23 18:37
(Received via mailing list)
On 23.05.2007 16:24, Josselin wrote:
>
> if d > 1.0   i print   "env. 1.257 km"
> I'd like to print "env. 1.2 km"  shoudl I round it again ? or is there
> any DRY solution ?

Is this good enough?

irb(main):010:0> "%.2f" % 1.000
=> "1.00"
irb(main):011:0> "%.2f" % 1.005
=> "1.00"
irb(main):012:0> "%.2f" % 1.006
=> "1.01"

Your values

irb(main):007:0> [0.2568915421 , 1.2568910001,  20.3256941254].map {|f|
"%10.2f" % f}
=> ["      0.26", "      1.26", "     20.33"]
irb(main):008:0> [0.2568915421 , 1.2568910001,  20.3256941254].map {|f|
"%.2f" % f}
=> ["0.26", "1.26", "20.33"]

Kind regards

  robert
Josselin (Guest)
on 2007-05-24 09:50
(Received via mailing list)
On 2007-05-23 16:34:50 +0200, Robert K. <removed_email_address@domain.invalid>
said:

>>    return "(env. " + d.to_s + " km)"
> => "1.00"
> => ["0.26", "1.26", "20.33"]
>
> Kind regards
>
>   robert

thanks a lot.. did not know about that...   using too much the rails
helpers...
fuunny,  it's like speaking a foreign language like spanish when you
know italian... similarities but also new stuff and slang ;-))
This topic is locked and can not be replied to.