sql server round function not working well

时光总嘲笑我的痴心妄想 提交于 2020-04-30 07:41:59

问题


I am using sql server 2000 and facing round function issue like the following statement working fine.

SELECT ROUND(5 * 7.83, 1)

The result will be 39.2

But when I get these values from the table, it gives 39.1, meaning it truncates and does not round up.

SELECT ROUND(rate * qty, 1) 
  FROM tbl

The result will be 39.1

rate and qty columns data types are float. Insert 5 in qty and 7.83 in rate, then check it. How I can fix it?


回答1:


Convert the table values to real,

SELECT ROUND(convert(real,rate)*convert(real,qty),1)



回答2:


Your sample simply query is not reflective of the data types involved.

Try these two instead:

SELECT ROUND(5 * 7.83, 1)
SELECT ROUND(cast(5 as float) * cast(7.83 as float), 1)

The 2nd one matches your table data types. Float datatypes are not meant for precise decimal calculations, use a decimal type for those instead.

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Without losing too much precision for normal numbers, you can just cast to decimal on the fly to force human-comprehensible decimal arithmetics, e.g.

SELECT ROUND(cast(rate as decimal(10,5)) * cast(qty as decimal(10,5), 1) 
  FROM tbl


来源:https://stackoverflow.com/questions/9460089/sql-server-round-function-not-working-well

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!