为了账号安全,请及时绑定邮箱和手机立即绑定

C#中函数怎样去掉末尾的0和小数点?

C#中函数怎样去掉末尾的0和小数点?

C#
HUH函数 2018-11-20 09:05:01
C#中函数怎样去掉末尾的0和小数点
查看完整描述

1 回答

?
婷婷同学_

TA贡献1844条经验 获得超8个赞

c#:
1:如果是textBox等控件值过滤0的话,可以使用TrimEnd('0')的方法;
eg:this.textBox1.Text.TrimEnd('0'),textBox1值为0.9900,则显示为0.99
2:使用ToString("g0")的方法
eg:0.99991000000000000.ToString("g0") 返回的值为0.99991
MSSQL中:
1:将小数用CAST函数转换
eg:select cast(0.2000 as real) 返回为 0.2
但是此方法常常因为转换的精度的问题,是数据与实际数据由差距
2:使用自定义函数转换
eg:

create function f_convert(@a decimal(20,8))
returns varchar(20)
as
begin
declare @re varchar(20),@r2 varchar(20),@i int
select @re=convert(varchar(20),@a)
,@i=charindex('.',@re)
,@r2=reverse(substring(@re,@i,20))
,@r2=reverse(substring(@r2,patindex('%[^0]%',@r2),20))
,@re=left(@re,@i-1)
if @r2<>'.' set @re=@re+@r2
return(@re)
end
go

--测试数据
declare @tb table(a decimal(20,8))
insert into @tb
select 0.20
union all select 0.21
union all select 0.21989

--查询
select a,转换后=dbo.f_convert(a) from @tb
go

--删除函数
drop function f_convert

/*--测试结果
a 转换后
---------------------- --------------------
.20000000 0.2
.21000000 0.21
.21989000 0.21989

(所影响的行数为 3 行)
--*/



查看完整回答
反对 回复 2018-12-07
  • 1 回答
  • 0 关注
  • 1794 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信