Sam
Sam

Reputation: 5260

Convert exponentials to decimal in ruby

I have output like the following exponential numbers.

6.0e-07

8.1e-07

1.1e-09

But I want above numbers should be displayed like below

0.00000060

0.00000081

0.0000000011

I mean in the form decimal format. I surfed in the net. I could not find any solution for this.

Is it possible in ruby?. if yes How to do that?.

Upvotes: 3

Views: 3043

Answers (2)

Stefan
Stefan

Reputation: 114208

You could use BigDecimal#to_s:

require 'bigdecimal'

BigDecimal.new('6.0e-07').to_s('F') #=> "0.0000006"
BigDecimal.new('8.1e-07').to_s('F') #=> "0.00000081"
BigDecimal.new('1.1e-09').to_s('F') #=> "0.0000000011"

Upvotes: 6

tadman
tadman

Reputation: 211660

Scientific notation is standard when the number is too large or too small to be displayed in a meaningful way.

The best way to present the numbers the way you'd prefer is using string format controls:

'%.10f' % 8.1e-07
# => "0.0000008100"

If you don't like the trailing zeroes, you can always trim those off with something like .sub(/0+$/, ''), though being careful not to convert 0.0 to 0..

Upvotes: 2

Related Questions