Josh Cheek wrote:
> It would probably be easier if you provided a set of tests we could
> check
> our function against, where we could be confident our function was
> correct
> once it passed all the tests.
Here are some examples of what it should do:
Delete any characters other than digits, +, -, e, E, or .:
'-24.5fge4x'5 => '-24.5e45'
Delete any extra decimals:
'2.4.5' => '2.45'
'2..45' => '2.45'
Delete any decimals in an exponent:
'245e7.6' => '2.45e76'
Delete any extra or misplaced + or – signs:
'+45-68+e+45-' => '4568e+45'
Delete any extra or misplaced ‘e’ or ‘E’ characters (first occurance of
'e' or 'E' has precedence unless it doesn't make sense):
'4.67e6e-7' => '4.67e67'
'+e4.67e-7' => '+4.67e-7'
The motivation for this is for a GUI input textbox, so that if the user
enters a bad string it automatically corrects it to a valid
floating-point representation in string form before converting to a
floating-point for calculations. I toyed with just doing
str = str.to_f.to_s
and letting Ruby figure out the floating point respesentation, but I'd
like more control over how the string is converted to floating point
representation. For example, I want
'2..45e9' => '2.45e9', whereas '2..45e9'.to_f.to_s => '2.0'
--Alex
--
Posted via
http://www.ruby-forum.com/.