简体   繁体   English

在varchar中处理小数时,SQL Server中的ROUND()

[英]ROUND() in SQL Server when dealing with a decimal in varchar

I know the usage of Round() and it works fine for 我知道Round()的用法,它可以正常工作

select round(147.26719,5,1)

which returns 147.26719. 返回147.26719。

Currently I am working on a table imported from a txt file so all the column are varchar , when I using round() to deal with a decimal in varchar like this 目前我正在处理从txt文件导入的表,所以所有列都是varchar ,当我使用round()来处理varchar中的小数时这样

select round('147.26719',5,1)

very weird it returns 147.26718. 非常奇怪,它返回147.26718。

I current make it run correctly as 我目前让它正常运行

select round(cast('147.26719', decimal(11,6)),5,1)

but can anybody explains to me why this happens? 但有人可以向我解释为什么会这样吗? I believe it is something when implicitly convert the varchar to decimal, but just don't know why. 我相信这是隐式将varchar转换为十进制的东西,但只是不知道为什么。

Thanks in advance 提前致谢

By default, the implicit conversion of the string for the round() is into a float , not a decimal. 默认情况下, round()的字符串的隐式转换是float ,而不是小数。 Floating point numbers are imprecise and might be off just a wee, wee bit from what you see -- but enough to matter. 浮点数是不精确的,可能只是一个小小的点,你看到的东西 - 但足够重要。

Your solution is the correct one -- cast to a decimal. 你的解决方案是正确的 - 投射到小数。

You can readily see this by using code such as: 您可以使用以下代码轻松地看到这一点:

select round('123.3', 1) as col
into x;

select *
from information_schema.columns
where table_name = 'x';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM