开发者

Setting default precision for all decimal numbers in rails

Is there a way to force Rails to output all decimal numbers with a certain precision? All of the decimal fields in my database are currency amounts, so I'd like decimal numbers to show by default with a precision of 2 (i.e. 2.40). I know I can use a helper function like "number_to_currency" to do this to each individual number, but that seems a bit tedious and unnecessa开发者_如何转开发ry.


If you're concerned about overriding "to_s" on Float having possible unforeseen side-effects, your next best bet is probably to just create a new method, but still as a core extension. Something like this:

class Float
    def c
        sprintf('%.2f', self)
    end
end

Then can't have any unforeseen consequences, and then anywhere you'd want to display the number with two decimal places, you'd just call .c. For example:

message = "The account balance is $#{amount.c}."

Not automatic, but not much extra typing, and no possible side-effects that overriding to_s could potentially cause.


Well if you don't mind monkey patching ruby, you can add a something like this (put it in an initializer at "/config/initializers/core_extensions.rb"):

class Float
    def to_s
        sprintf('%.2f', self)
    end
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜