SQL Server ROUND()不适用于以1结尾的FLOAT

我改变了我的例子以使用FLOAT ……太多人被挂在整个NVARCHAR上.我们不会将数据存储在数据库中作为NVARCHAR.我只是以NVARCHAR为例.我用FLOAT得到了相同的结果.

对于某些FLOAT,我们遇到了SQL Server ROUND()的问题

    DECLARE @EXCHANGE_RATE FLOAT
    SET @EXCHANGE_RATE = 1.327810000000000000000
    SELECT ROUND(@EXCHANGE_RATE,6,1)
    SET @EXCHANGE_RATE = 1.327820000000000000000
    SELECT ROUND(@EXCHANGE_RATE,6,1)

第一个返回:1.327809
第二个回报:1.32782

你会认为第一个会返回1.32781,而不是1.327809.

这是ROUND中的功能还是错误?有什么简单的方法吗?

谢谢!

基于Mat的将它们作为DECIMAL进行渲染的想法,这是有效的……它很丑陋,但有效.我使用10的原因是我查看了我们的数据库,这似乎是我们存储的最长数字.此外,我需要将其转换回FLOAT,因为他们不希望看到任何尾随0

    DECLARE @EXCHANGE_RATE FLOAT
    SET @EXCHANGE_RATE = 1.327810000000000000000
    SELECT CAST(ROUND(CAST(@EXCHANGE_RATE AS DECIMAL(28,10)),6,1) AS FLOAT)

最佳答案 试试这个查询.

SELECT
  ROUND('1.3278100',6,0)                     AS x0,
  ROUND('1.3278200',6,0)                     AS y0,
  ROUND('1.3278100',6,1)                     AS x1,
  ROUND('1.3278200',6,1)                     AS y1,

  ROUND(CAST( '1.3278100' AS FLOAT), 6, 0)   AS a0,
  ROUND(CAST( '1.3278200' AS FLOAT), 6, 0)   AS b0,
  ROUND(CAST( '1.3278100' AS FLOAT), 6, 1)   AS a1,
  ROUND(CAST( '1.3278200' AS FLOAT), 6, 1)   AS b1,

  ROUND(CAST( '1.3278100' AS DECIMAL(9,8)), 6, 0)   AS i0,
  ROUND(CAST( '1.3278200' AS DECIMAL(9,8)), 6, 0)   AS j0,
  ROUND(CAST( '1.3278100' AS DECIMAL(9,8)), 6, 1)   AS i1,
  ROUND(CAST( '1.3278200' AS DECIMAL(9,8)), 6, 1)   AS j1
;

http://sqlfiddle.com/#!6/d41d8/15607

这对我来说是指ROUND()在截断它们之前隐式地将你的VARCHAR值转换为FLOAT.

由于FLOAT无法准确表示1.327810,因此您实际上截断了1.3278099999999(或类似的东西).

因此,简而言之,在截断之前将它们明确地转换为DECIMAL.或者只是不将数字数据存储为字符串……

点赞