gpt4 book ai didi

ruby-on-rails - 在 RABL 模板中,如何舍入一些数字而不舍入其他数字?

转载 作者:太空宇宙 更新时间:2023-11-03 18:23:07 25 4
gpt4 key购买 nike

在我的应用程序的 JSON 输出中,我需要将大部分非整数(即 float )数值显示为四舍五入到一位小数,即 1.7777 将显示为 1.8。

我是通过猴子修补 Float 的 as_json 方法来做到这一点的:

class Float
def as_json(options={})
self.round 1
end
end

我什至不确定这是否是个好主意,我刚刚这样做是因为我不知道如何在我的 RABL 模板中指定数值格式。

但现在我还需要显示某些值(纬度和经度)而不进行任何舍入:

object @foo
attributes :bar, :latitude, :longitude

我如何告诉 RABL 舍入某些值(条)而不舍入其他值(纬度、经度)?

最佳答案

要在原始上下文中回答您的问题,在 RABL 模板中,您只需为需要额外处理的那些属性创建自定义节点,例如

object @foo
attributes :bar
node(:latitude) { |foo| f.latitude.round(1) }
node(:longitude) { |foo| f.longitude.round(1) }

关于ruby-on-rails - 在 RABL 模板中,如何舍入一些数字而不舍入其他数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14803937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com