views:

60

answers:

2

How do I check a value starting with a decimal

is_a_number(value) .... works for 12, 12.0, 12.2, 0.23 but not .23

Basically I'm doing a validation in a form, and I want to allow values starting with . i.e .23 but obviously pop up a flag (false) when its not a number

+1  A: 

".23" isn't really a number, in my book.

If you want to treat it like one, check if the first character is a decimal point, if it is, prepend a "0" and try again.

Actually, you could probably prepend a zero regardless. It shouldn't affect the value of any "legitimate" number. (EDIT: As long as you can explicitly specify base 10 when actually converting to a number)

Anon.
If a number has a leading zero and the second character isn't a decimal point, the number will be treated as an octal value (for example, "10" = "ten" but "010" = "eight"). Blindly prepending a zero character probably won't give you the behavior you are looking for.
bta
That is true. Unless you specify an explicit base, it will cause problems.
Anon.
+1  A: 

Read your input into a string and dynamically add the zero if needed. For example:

if (inputvar[0] == '.')
  inputvar = "0#{inputvar}"
end

The resulting value can be converted into a number by .to_i, .to_f, etc.

bta