我有一个浮动属性,我的精度有问题。如果保存类似" 745.34"的值,它会正确保存到数据库。但是,如果我尝试保存4564523.845,例如,它会保存4564520.0。猜猜它并不是一个浮动数不大的数字。我的控制台的一些例子:
c.valor_total = 4564523.845
=> 4564523.845
2.3.1 :034 > c.save
(0.3ms) BEGIN
UnidadeConsumidora Load (0.3ms) SELECT `unidade_consumidoras`.* FROM `unidade_consumidoras` WHERE `unidade_consumidoras`.`id` = 28 LIMIT 1
SQL (21.2ms) UPDATE `contas` SET `valor_total` = 4564523.845, `updated_at` = '2016-10-20 17:28:20' WHERE `contas`.`id` = 28
(70.4ms) COMMIT
=> true
2.3.1 :035 > c = Conta.find 28
Conta Load (0.9ms) SELECT `contas`.* FROM `contas` WHERE `contas`.`id` = 28 LIMIT 1
=> #<Conta id: 28, unidade_consumidora_id: 28, razao_social: "DROGARIA ARAUJO S A", ano: 2016, mes: 8, numero_cliente: "7000042467", cnpj: "17.256.512/0001-16", consumo_kwh: "10942", vencimento: "2016-10-18", valor_total: 4564520.0, created_at: "2016-10-19 18:43:35", updated_at: "2016-10-20 17:28:20", pdf_conta: "ADOLPHO_COTTA.pdf", unidade_de_leitura: "07020129", cod_instalacao: "3000728720", logradouro: "PCA ALEXANDRE LANZA 141 CO .", bairro: "CENTRO", cep: "35700-040", municipio: "SETE LAGOAS", uf: "MG">
2.3.1 :036 > c.valor_total
=> 4564520.0
在更新sql日志中看到这个值是正确的...那么它可以是什么以及我如何修复它?
编辑:
schema.rb for contas:
create_table "contas", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
t.integer "unidade_consumidora_id"
t.string "razao_social"
t.integer "ano"
t.integer "mes"
t.string "numero_cliente"
t.string "cnpj"
t.string "consumo_kwh"
t.date "vencimento"
t.float "valor_total", limit: 24
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "pdf_conta"
t.string "unidade_de_leitura"
t.string "cod_instalacao"
t.string "logradouro"
t.string "bairro"
t.string "cep"
t.string "municipio"
t.string "uf"
t.index ["unidade_consumidora_id"], name: "index_contas_on_unidade_consumidora_id", using: :btree
end
答案 0 :(得分:2)
我很确定你那里有“错误”的数据库类型。
Conta.columns_hash['valor_total'].type
很可能会返回"integer"
,而如果您的目标是存储精确的数字,那么您希望获得decimal
。
我建议更改数据类型:
change_column :contas, :valor_total, :decimal, precision: 5, scale: 2
您使用过float
数据类型,但没有指定精度。即使您可能(从未看到使用过的float
数据库类型)可以更改并指定它,我仍然建议使用decimal
来进行此类操作,因为它不会进行任何舍入等等。计算,因此您将始终拥有最精确的数字。