Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a scientific notation string to decimal notation?

Tags:

regex

ruby

I'd like to find and convert all scientific notation strings in a csv file to decimal notation, e.g.:

1.0e-05 to 0.00001

How can I do that in ruby?

like image 392
ohho Avatar asked Dec 21 '11 07:12

ohho


People also ask

How do you convert a string to a decimal?

Converting a string to a decimal value or decimal equivalent can be done using the Decimal. TryParse() method. It converts the string representation of a number to its decimal equivalent.

How do you convert scientific notation to decimal form in Java?

You can do it like this: double d = 1.999e-4; NumberFormat nf = NumberFormat. getInstance(); nf. setMinimumFractionDigits(7); System.


2 Answers

Just use string conversion. The necessary coercion to float will be done automatically:

"%f" % "1.0e-05"
=> "0.000010"

# Which, behind the scenes is the same as:
"%f" % "1.0e-05".to_f
=> "0.000010"

Adjust as necessary to get more or less accuracy. For example:

"%.5f" % "1.0e-05"
=> "0.00001"

If you want to get real fancy and chop off unnecessary zeros at the end, here's one way. (Hopefully someone will suggest something more elegant; I couldn't think of anything):

("%.20f" % "1.0e-05").sub(/\.?0*$/, "")
=> "0.00001"
like image 105
Peter Avatar answered Sep 22 '22 16:09

Peter


If you're interested in doing any sort of math on a number and it is too small:

"%f" % "1.0e-10"
=> "0.000000"

# not so good for various reasons
("%f" % "1.0e-10") == ("%f" % "1.0e-8")
=> true

You can use BigDecimal:

BigDecimal.new "1.0e-10"
=> #<BigDecimal:7ffdf6c38678,'0.1E-9',9(18)>
like image 40
efatsi Avatar answered Sep 21 '22 16:09

efatsi