开发者

check value starting with decimal ruby on rails

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 (f开发者_高级运维alse) when its not a number


".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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜