Printing float to string with decimal rounding


#1

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


#2

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


#3

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


#4

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 ;-))