如何计算浮点列中小数点右侧的位数?
我有一个带有纬度和经度的表,它们存储为浮点。如何计算“纬度”列中小数点右侧的位数?数据看起来像这样:
DECLARE @MyData TABLE (ID, Latitude float, Longitude float)
INSERT @MyData
SELECT 'A', 33.11, -55.2235 UNION ALL
SELECT 'B', 33.6407760431,-87.0002760543 UNION ALL
SELECT 'C', 42.2997,-70.9081;
我希望在
ID | LatitudeNumberOfDigits
A | 2
B | 10
C | 4
尝试将其转换为文本并使用 .作为分隔符,但 CONVERT 没有按预期工作。它四舍五入到四位有效数字
SELECT ID, Latitude, Longitude,
CONVERT(varchar(max),[Latitude]) AS LatText
FROM @MyData
给了我
ID Latitude Longitude LatText
A 33.11 -55.2235 33.11
B 33.6407760431 -87.0002760543 33.6408
C 42.2997 -70.9081 42.2997
谢谢!
I have table with Latitudes and Longitudes that are stored as floating points. How would I count the number of digits to the right of the decimal in the Latitude column? The data would look something like this:
DECLARE @MyData TABLE (ID, Latitude float, Longitude float)
INSERT @MyData
SELECT 'A', 33.11, -55.2235 UNION ALL
SELECT 'B', 33.6407760431,-87.0002760543 UNION ALL
SELECT 'C', 42.2997,-70.9081;
and I would want this in
ID | LatitudeNumberOfDigits
A | 2
B | 10
C | 4
I was trying to convert it to text and split it up using a . as a delimiter but the CONVERT did not work as anticipated. It rounded to four significant digits
SELECT ID, Latitude, Longitude,
CONVERT(varchar(max),[Latitude]) AS LatText
FROM @MyData
Gave me
ID Latitude Longitude LatText
A 33.11 -55.2235 33.11
B 33.6407760431 -87.0002760543 33.6408
C 42.2997 -70.9081 42.2997
Thanks !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
试试这个(假设你的浮点数最多有 10 位小数,否则调整 STR 中的值)。
然而,正如其他人所指出的,FLOAT 可能会给您带来一些麻烦。
例如考虑这个:
Try this (it assumes that your floats will have at most 10 decimal places, otherwise adjust the values in STR).
As others have note, however, FLOATs are likely to give you some headaches.
Consider this for instance:
你不知道。小数位数由 SQL 中浮点数的大小决定。您看到的数量取决于浮动格式的方式。
You don't. The number of decimal places is determined by the size of a float in SQL. How many you SEE is determined by the way the float is formatted.
使用 DECIMAL 而不是 FLOAT:
返回:
Use DECIMAL not FLOAT:
Returns:
转换为数字(最大精度,最大比例)。然后用 case 语句进行迭代。
Cast as numeric(maxprecision, maxscale). Then iterate with a case statement.
这可能不是有效的 tsql,但它会很接近:
This may not be valid tsql, but it will be close:
使用
STR
函数而不是CONVERT
或CAST
。它允许您更好地控制小数位数和字符串的总长度。请参阅STR (Transact-SQL)Use the
STR
function instead ofCONVERT
orCAST
. It allows you more control on the number of decimals and the total length of the string. See STR (Transact-SQL)