rails decimal keep three position after point

本文介绍了如何在Ruby on Rails中为decimal类型的数据库字段指定精度和小数位数,以提高数值存储的准确性,并通过示例展示了如何定义latitude和longitude字段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

Rails Tip: Precision and scale for decimals

For when you need that little bit of extra accuracy, specifying precision and scale for a decimal column in your Ruby on Rails migration is pretty simple. The precision represents the total number of digits in the number, whereas scale represents the number of digits following the decimal point. To specify the precision and scale, simply pass those as options to your column definition.

For example:

class AddLatLngToAddresses < ActiveRecord::Migration
  def self.up
    add_column :addresses, :lat, :decimal, :precision => 15, :scale => 10
    add_column :addresses, :lng, :decimal, :precision => 15, :scale => 10
  end

  def self.down
    remove_column :addresses, :lat
    remove_column :addresses, :lng
  end
end

This will allow you to have 10 digits after the decimal point and 15 digits max.

One thing to note, however is that Rails will use BigDecimal as the type for the column. BigDecimal provides support for very large or very accurate floating point numbers. Remember those pesky floating point imprecision errors?

>> 1.2 - 1.0 == 0.2
=> false

Yep, BigDecimal handles that…

>> BigDecimal.new('1.2') - BigDecimal.new('1.0') == BigDecimal.new('0.2')
=> true

So now, go forth and be accurate.

Also see

 

 

 

Posted April 12th, 2008 at 3:52 am in  Ruby on Rails |  Permalink

Comment (1)

 
Relatively new to Rails and never took the time to understand this simple idea. I just keep Googling it until today, when I realized it would be much better if I just took a few seconds to understand what 'precision' and 'scale' actually did. 

Thanks for the clear explanation, quick and easy...
 

Post a new comment

Comments by

 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值