开发者

Format number if the function returned a number and its a float

my_number = get_salary_range(user)

Right now my method may return 324234.23424222

I want it to be:

2342343.23

(two decimal places)

But I have to gaurd against the return valu开发者_运维技巧e being nil, or '' etc.

How can I do this safely?


The solution depends on what you want in your string when my_number.nil? is true. Forcibly converting things to Float would be a reasonable starting point:

formatted_number = '%.2f' % my_number.to_f

That will handle the expected numeric my_number values as well as nil, "nonsense", and '' (with the latter three producing 0.00).

If you want to more thorough, then you can ask your my_number if it understands to_f:

formatted_number = '%.2f' % (my_number.respond_to?(:to_f) ? my_number.to_f : 0.0)

But you're still left to decide what should happen if my_number cannot be sensibly converted to a Float.

You can go one step further and make the "what about things that aren't Float-ish" configurable:

def numberify(thing, default = "0.00")
    return thing.respond_to?(:to_f) \
         ? '%.2f' % thing.to_f \
         : default
end

Further configurability is left as an exercise for the reader.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜