如何从mssql中数据类型为real的列中获取可读值

时间:2014-02-08 18:33:47

标签: php sql-server floating-point sqldatatypes

I have some Spec data(LSL/USL) something like this, 
with data type real, 
if I query with MSSQL Server Management Studio(MSSMS for short), 
it's displayed as 0.45, 
but if I query with php via sqlsrv driver for php4.4, 
I got 0.44999998807907, but I need to get it just exactly same in MSSMS,
and it's not just rounding issue, 
ex: 
php => 0.00030000001424924, MSSMS => 0.0003
php => 0.0049999998882413, MSSMS => 0.005
php => 0.0049000000581145, MSSMS => 0.0049

和!!!!上面的示例是相同的列,因此无法通过简单地应用于ROUND()来解决。

I know real is Approximate Numerics,
And so it's reasonable to get this, 
but I need a workaround,
we didn't have this issue when we use asp or vb,
probably some implicit casting by data driver, 

anyway, any advice or comment is welcome.
**First, I want say "Thank You" to all of you guys taking time to help me.**
but this question probably more tricky actually,
sorry I didn't show enough example to guide you to right way,
DECLARE @TABLE TABLE(VALUE REAL)
INSERT INTO @TABLE VALUES
(0.00030000001424924),(0.0049999998882413),(0.0049000000581145),
(0.000099999997473788),(0.60000002384186),(0.000039999998989515),
(0.00025000001187436)

SELECT  CAST(VALUE AS DECIMAL(10,4)) AS [Decimal Values] 
       ,ROUND(VALUE, 4)              AS [Rounded values]
       ,CAST(VALUE AS NUMERIC(10,4)) AS [Numeric Values]
FROM @TABLE
in above case, 
0.00025000001187436 should be 0.00025 in MSSMS, but we will get 0.0003
0.000039999998989515 should be 4E-05.

How do we simulate and get same result in PHP query?
Is that possible? 

And, What if I decide change the datatype from real to decimal,
what is correct precision for decimal? decimal(?, ?)
to not losing precision.

1 个答案:

答案 0 :(得分:0)

有几种方法可以做到这一点,如Aaron所建议的,以及其他一些如下

测试数据

DECLARE @TABLE TABLE(VALUE REAL)
INSERT INTO @TABLE VALUES
(0.00030000001424924),(0.0049999998882413),(0.0049000000581145)   

<强>查询

SELECT  CAST(VALUE AS DECIMAL(10,4)) AS [Decimal Values] 
       ,ROUND(VALUE, 4)              AS [Rounded values]
       ,CAST(VALUE AS NUMERIC(10,4)) AS [Numeric Values]
FROM @TABLE

结果集

╔════════════════╦════════════════╦════════════════╗
║ Decimal Values ║ Rounded values ║ Numeric Values ║
╠════════════════╬════════════════╬════════════════╣
║ 0.0003         ║ 0.0003         ║ 0.0003         ║
║ 0.0050         ║ 0.005          ║ 0.0050         ║
║ 0.0049         ║ 0.0049         ║ 0.0049         ║
╚════════════════╩════════════════╩════════════════╝