任何人都可以解释为什么这个比较失败从浮动铸造?

时间:2016-07-12 09:45:39

标签: sql sql-server tsql casting floating-point

我正在使用Microsoft Server SQL。

我不确定为什么会这样。到目前为止,我唯一的geuss是引擎盖下的值为32.49999。但是当使用32.32等不同的值时,相同的等式不会失败。

任何人都可以解释为什么会这样吗?

Simple test

select 
cast(32.55 as float)
,cast(32.55 as float) * 1000
,case when cast(32.55 as float) * 1000 <> 32550 then 'F' ELSE 'C' END as [vanilla]
,case when cast(cast(32.55 as float) * 1000 as int) <> cast(32550 as int) then 'F' ELSE 'C' END as [int]
,case when cast(cast(32.55 as float) * 1000 as varchar(max)) <> cast(32550 as varchar(max)) then 'F' ELSE 'C' END as [varchar]
,case when cast(cast(32.55 as float) * 1000 as float) <> cast(32550 as float) then 'F' ELSE 'C' END as [float]
,case when round(cast(32.55 as float) * 1000,0) <> round(32550,0) then 'F' ELSE 'C' END as [round]
,case when cast(cast(32.55 as float) * 1000 as decimal(18,2)) <> cast(32550 as decimal(18,2)) then 'F' ELSE 'C' END as [decimal]

1 个答案:

答案 0 :(得分:0)

这是由于'向下'试试这个 select cast(cast(32.55 as float)* 1000 as int)

我得到32549

您的32550被视为32549.99999 ......并向下舍入

  • 你需要ROUND到零小数位,即使你认为你在处理整数之前也是如此。

e.g

选择cast(ROUND(cast(32.55 as float)* 1000,0)为int)

对于你的名为FLOAT的例子 - 存在不同的“隐藏”小数,这意味着如果从另一个中减去一个,你会得到一个非零的小答案

尝试这个

    select 
    cast(cast(32.55 as float) * 1000 as float), 
    cast(32550 as float),
    cast(cast(32.55 as float) * 1000 as float) -  cast(32550 as float),  --this gives non zero answer, indicating that the internal values have different values in the higest decimal places
    case when cast(cast(32.55 as float) * 1000 as float) <> cast(32550 as float) then 'F' ELSE 'C' END as [float]