如何只删除最后一个尾随零? [英] How can I remove only the last trailing zero?

查看:98
本文介绍了如何只删除最后一个尾随零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何删除十进制数据类型的一个尾随零,例如参考下面的示例数据。

How can i remove the one trailing zero for a decimal datatype, for example refer below sample data.

Input Values  >> Expected output values 
1)29.36       >> 29.36
2)29.00       >> 29.0
3)20.00       >> 20.0
4)29.50       >> 29.5
5)20          >> 20





我的尝试:



我试图使用浮点数据类型但是如果输入值是29.00它只显示为29但我希望它是29.0。

字符串格式在这种情况下似乎也是准确的我需要删除第二个十进制值,只有它为零。



What I have tried:

I tried to use float data type but if the input value is 29.00 it is showing as 29 only but i want it to be 29.0.
string formats also seems to be in accurate in this case as i need to remove second decimal value only if it zero.

推荐答案

尝试格式字符串:0.0#

Try a format string: "0.0#"
decimal d;
d = 29.36M;
Console.WriteLine("{0}:{0:0.0#}", d);
d = 29.00M;
Console.WriteLine("{0}:{0:0.0#}", d);
d = 20.00M;
Console.WriteLine("{0}:{0:0.0#}", d);
d = 29.50M;
Console.WriteLine("{0}:{0:0.0#}", d);

给予:

Gives:

29.36:29.36
29.00:29.0
20.00:20.0
29.50:29.5


除了OriginalGriff的解决方案#1之外,我建议你阅读:浮动点揭秘,第1部分 [ ^ ]并且:每个计算机科学家应该知道的关于浮点算术的内容 [ ^ ]



结论:你想在自定义中显示小数值格式。



标准数字格式字符串| Microsoft Docs [ ^ ]

自定义数字格式字符串| Microsoft Docs [ ^ ]
In addition to solution #1 by OriginalGriff, i'd recommend to read this: Floating Point Demystified, Part 1[^] and this: What Every Computer Scientist Should Know About Floating-Point Arithmetic[^]

Conclusion: you want to display decimal value in custom format.

Standard Numeric Format Strings | Microsoft Docs[^]
Custom Numeric Format Strings | Microsoft Docs[^]


这篇关于如何只删除最后一个尾随零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆