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?
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.
You can do it like this: double d = 1.999e-4; NumberFormat nf = NumberFormat. getInstance(); nf. setMinimumFractionDigits(7); System.
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"
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)>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With