gpt4 book ai didi

ruby-on-rails - 价格的 Ruby 正则表达式

转载 作者:数据小太阳 更新时间:2023-10-29 08:40:27 24 4
gpt4 key购买 nike

当末尾为零时,这个失败

12.12 次传球5.51 传球12.50 失败12.60 失败

 price_regex = /^\d+(\.\d{2})?$/

为什么?我该如何解决?

更多信息

在 _form.html.erb 中

  <p>
<%= f.label :price %><br />
<%= f.text_field :price %>
</p>

在 menu_item.rb 中

  price_regex = /^\d+(\.\d{2})?$/
validates :price, :presence => true,
:format => { :with => price_regex }

在 menu_items_controller.rb 中

  def create
@menu_item = MenuItem.new(params[:menu_item])

if @menu_item.save
respond_with @menu_item, :location => menu_items_url
else
flash[:notice] = "Not Saved"
end
end

price是数据库中的小数,精度为2。

最佳答案

你说 price 是“数据库中精度为 2 的小数”。这意味着 price 在 Ruby 中表示为 BigDecimal,并且正则表达式测试将在该 BigDecimal 的字符串形式上完成。一点点实验会澄清事情:

> p = BigDecimal.new('12.50')
=> #<BigDecimal:12a579e98,'0.125E2',18(18)>
> p.to_s
=> "12.5"

因此您的正则表达式将失败。您根本不应该为此使用正则表达式,正则表达式适用于字符串,但您正在检查一个数字。如果您允许转换,您应该能够继续使用您的正则表达式:

/^\d+(\.\d{1,2})?$/

关于ruby-on-rails - 价格的 Ruby 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8117155/

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