【问题标题】:Storing multiple currencies in Postgres, using rails使用 Rails 在 Postgres 中存储多种货币
【发布时间】:2023-03-06 20:12:01
【问题描述】:

我有一个处理来自不同国家的产品价格的 rails 应用程序。 存储英镑和美元工作正常。但是,当我开始处理具有 3 位小数的 CLP(智利比索)时,它的存储不正确。

例如,我尝试插入 799.990,但当它以 799.99 存储时。这并不理想,因为价格可能是 799.99。

我将价格设置为t.decimal :price, precision: 19, scale: 4,所以这应该涵盖大多数货币。

那么,我的问题是有什么方法可以用尾随 0 存储价格?还是我遗漏了什么,有没有更好的方法来处理铁路中的货币?


更新: 在 StackOverflow 上搜索了一下之后,我认为这可能是一种更简单的货币处理方式。

number_to_currency locale converting

【问题讨论】:

    标签: ruby-on-rails postgresql currency


    【解决方案1】:

    由于 799.99 与 799.990 的金额相同,您不需要修改数据库列以存储尾随的“0”。您可以简单地编辑视图以显示小数点后 3 位:

    <% if @product.currency == 'CLP' %>
      Price: <%= '%.3f' % @product.price %>
    <% else %>
      <!-- Existing logic -->
    <% end %>
    

    更新

    另一种选择是使用sprintf

    <%= sprintf('%.3f', @product.price) %>
    

    【讨论】:

      【解决方案2】:

      正如 Jagdeep 在他的回答中已经写的那样,您只需要在将数字呈现到页面时对其进行格式化。

      我会为此使用 Rails 的 number_to_currency 助手:

      CURRENCY_OPTIONS = { 
        'CLP' => { unit: '$', precision: 3 },
        'EUR' => { unit: '€', precision: 2 },
        'USD' => { unit: '$', precision: 2 } 
      }
      
      number_to_currency(price, CURRENCY_OPTIONS[currency])
      

      【讨论】:

        猜你喜欢
        • 2013-04-23
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        • 2014-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        相关资源
        最近更新 更多