如何validation数值的小数?

我在模型中的validation如下:

validates_numericality_of :shoe_size, :message=>'Please input a number' 

但这还不够,因为用户可以输入一些像“42.22222222121212121212 …”这样的值,这是不可取的。 那么,如何validation输入只有两个小数,如42.22

你可以试试这个:

 validates_format_of :shoe_size, :with => /^\d+\.*\d{0,2}$/ 

@warren回答但拿出*并放一个? 因为你可以做3 ….. 0但是? 你可以有零或一个。

  :with => /^\d+\.?\d{0,2}$/ 

建立@Bitterzoet的答案,但仍然使其成为validation(通过validate方法 ):

 class Product < ApplicationRecord # Whatever other validations you need: validates :price, numericality: {greater_than_or_equal_to: 0} # then a custom validation for precision validate :price_is_valid_decimal_precision private def price_is_valid_decimal_precision # Make sure that the rounded value is the same as the non-rounded if price.to_f != price.to_f.round(2) errors.add(:price, "The price of the product is invalid. There should only be two digits at most after the decimal point.") end end end 

收到后为什么不按摩输入? 你应该在我看来将它四舍五入到自己的两位小数,而不是让用户担心。

Rails提供round_with_precision,所以只需在你的浮点数上调用.round(2)就会将其四舍五入为2位小数。

sprintf Ruby类提供了指定要显示的小数位数的能力。例如。 在下面的例子中,我得到了一个轨道的平均评级,并确保平均值四舍五入到小数点后1位。

 sprintf("%.1f",track.ratings.average('rating'))