使用STR将SQL Float转换为VARCHAR

时间:2017-02-02 18:07:15

标签: sql sql-server

我尝试使用STR函数将浮点值转换为具有2位小数精度的字符串值。效果很好,但在尝试转换1.525的值时我得错了号码。我应该得到1.53,而我得到1.52。

Does not work
Select rtrim(ltrim(Str(1.525, 10,2)))       
1.52

Works for these    
Select rtrim(ltrim(Str(1.225, 10,2)))       
1.23

Select rtrim(ltrim(Str(1.325, 10,2)))       
1.33

Select rtrim(ltrim(Str(1.515, 10,2)))       
1.52

Select rtrim(ltrim(Str(1.535, 10,2)))   
1.54

更新

我使用FORMAT(floatValue, 'N2')并且它现在正常工作。有关使用此功能的任何评论,2012年开始支持。第二个参数也可以动态构造以支持不同的精度

1 个答案:

答案 0 :(得分:1)

如果您的目标是将字符串转换为数字类型(舍入为两位小数),然后对其执行其他操作,我将100%使用m = this.x[y]; this.x[y] = this.x[y + 1]; this.x[y + 1] = m; // reflect the above swaps when updating 'this.square' this.square[y].changeY(this.x[y]); this.square[y + 1].changeY(this.x[y + 1]); (或CAST()) ,可能使用CONVERT()和其他函数,但在您的情况下,与ROUND()一起使用的精度会为我们舍入。

以下是问题查询的另一种形式:

CAST()

为什么你要坚持使用Select cast(cast('1.525' as numeric(10, 2)) as varchar(11)); -- returns '1.53' -- note that I don't really have to recast it as a varchar, -- but that's what type your example query would return, -- so I tried to match that 呢?