在轨道模型验证红宝石浮点精度 [英] floating point precision in ruby on rails model validations

查看:137
本文介绍了在轨道模型验证红宝石浮点精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用正则表达式来验证美元数额:
^ [0-9] + \。[0-9] {2} $

这可以正常工作,但是当用户提交表单并且美元金额以0(零)结尾时,ruby(或者rails?)会将0关闭。
因此500.00变成了500.0,因此不能正确验证。



有没有办法让ruby / rails保持用户输入的格式,零美元?

解决方案

我假设您的美元金额是十进制类型。因此,在保存到数据库之前,用户在字段中输入的任何值都将从字符串转换为适当的类型。验证适用于已经转换为数字类型的值,所以正则表达式在你的情况下并不是一个合适的验证过滤器。



你有几个可能的解决方法:


  1. 使用 validates_numericality_of 。这样你完全转换到Rails,并检查数量是否在给定的范围内。
  2. 使用 validate_each 方法和你自己编写你的验证逻辑(比如检查这个值是否有两位以上的十进制数字)。
  3. 验证
    $ b


  4. >这在
    验证情况下特别有用,其中用户
    可能为整数
    字段提供一个字符串,并且想要将
    原始字符串显示回错误
    消息。访问属性
    通常会将字符串转换为
    0,这不是您想要的。


    所以,你应该可以使用:

      validates_format_of:amount_before_type_cast,:with => /^[0-9]+\.[0-9]{2}$/,:message => 必须包含美元和美分,以期间

    分开,但请注意,用户可能会发现它单调乏味地遵守刚性的入门规则(例如,我真的希望能够输入 500 ,而不是 500.00 ),而且在某些地区时期不是小数点分隔符(如果您打算将您的应用程序国际化)。

    I am trying to validate a dollar amount using a regex: ^[0-9]+\.[0-9]{2}$

    This works fine, but whenever a user submits the form and the dollar amount ends in 0(zero), ruby(or rails?) chops the 0 off. So 500.00 turns into 500.0 thus failing the regex validation.

    Is there any way to make ruby/rails keep the format entered by the user, regardless of trailing zeros?

    解决方案

    I presume your dollar amount is of decimal type. So, any value user enters in the field is being cast from string to appropriate type before saving to the database. Validation applies to the values already converted to numeric types, so regex is not really a suitable validation filter in your case.

    You have couple of possibilities to solve this, though:

    1. Use validates_numericality_of. That way you leave the conversion completely to Rails, and just check whether the amount is within a given range.
    2. Use validate_each method and code your validation logic yourself (e.g. check whether the value has more than 2 decimal digits).
    3. Validate the attribute before it's been typecasted:

    This is especially useful in validation situations where the user might supply a string for an integer field and you want to display the original string back in an error message. Accessing the attribute normally would typecast the string to 0, which isn‘t what you want.

    So, in your case, you should be able to use:

    validates_format_of :amount_before_type_cast, :with => /^[0-9]+\.[0-9]{2}$/, :message => "must contain dollars and cents, seperated by a period"
    

    Note, however, that users might find it tedious to follow your rigid entry rules (I would really prefer being able to type 500 instead 500.00, for example), and that in some locales period is not a decimal separator (if you ever plan to internationalize your app).

    这篇关于在轨道模型验证红宝石浮点精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆