【问题标题】:How to return a Ruby float with 2 decimal places when displaying currency显示货币时如何返回 2 位小数的 Ruby 浮点数
【发布时间】:2019-06-04 18:19:23
【问题描述】:

我有一个 SQL 数据库,用于存储从 Ruby 类中的浮点数传入的价格,然后我需要随后将其显示在 HTML/erb 文件中。我的问题是 10.00 或 10.20 的价格返回为 10.0 或 10.2,然后在 HTML 中显示不正确。我需要在 Ruby 中将价格保持为浮点数,因为它们被用于计算......有没有一种明显的方法可以将这些价格返回到小数点后 2 位?

我尝试将它们以不同方式存储在我的 SQL 数据库中,我相信我可以尝试将浮点数转换为字符串并将其拆分为小数点,然后循环遍历该数组中的第二个元素并添加另一个零,如果单个数字,然后将数组作为字符串重新组合在一起 - 但我正在努力让它工作......

我的 Ruby 类是这样设置的:

class Transaction

  attr_accessor :amount, :merchant_id, :tag_id, :transaction_date
  attr_reader :id

  def initialize(options)

    @id = options['id'].to_i if options['id']
    @amount = options['amount'].to_f
    @merchant_id = options['merchant_id'].to_i if options['merchant_id']
    @tag_id = options['tag_id'].to_i if options['tag_id']
    @transaction_date = options['transaction_date'] if options['transaction_date']

  end

SQL 表同样:

CREATE TABLE transactions(
  id SERIAL8 PRIMARY KEY,
  amount DECIMAL(10,2),
  transaction_date DATE,
  merchant_id INT8 REFERENCES merchants(id) ON DELETE CASCADE,
  tag_id INT8 REFERENCES tags(id) ON DELETE CASCADE
);

当我在值数组上运行调试器时,我返回的所有内容都显示为浮点数,这与我在课堂上的定义方式一样...

【问题讨论】:

  • 永远不要将货币存储为浮点数。

标签: html sql ruby


【解决方案1】:

除了不将货币存储为浮点数的非常有效的评论之外,您就在您所在的位置,因此要显示带有 2 位小数的数字,您需要使用 http://ruby-doc.org/core-2.0.0/Kernel.html#method-i-sprintf

[1] pry(main)> sprintf('%.2f', 2)
=> "2.00"
[2] pry(main)> sprintf('%.2f', 2.569)
=> "2.57"
[3] pry(main)> sprintf('%.2f', 2.56)
=> "2.56"
[4] pry(main)> sprintf('%.2f', 2.56666666)
=> "2.57"

所以在你的代码中:

class Transaction

  attr_accessor :amount, :merchant_id, :tag_id, :transaction_date
  attr_reader :id

  def initialize(options)
    @id = options['id'].to_i if options['id']
    @amount = sprintf('%.2f', options['amount'].to_f)
    @merchant_id = options['merchant_id'].to_i if options['merchant_id']
    @tag_id = options['tag_id'].to_i if options['tag_id']
    @transaction_date = options['transaction_date'] if options['transaction_date']
  end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-10
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多