如何在不尾随零的情况下格式化小数 [英] How to format a decimal without trailing zeros

查看:73
本文介绍了如何在不尾随零的情况下格式化小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚了解到,小数点后会记住要存储数字需要多少尾随零。换句话说:它记住分数的大小。

I've just learned that a decimal somehow remembers how much trailaing zero's were needed to store a number. With other words: it remembers the size of the fraction.

例如:

123M.ToString() ==> resuls in: 123
123.00M.ToString() ==> resuls in: 123.00
123.450M.ToString() ==> resuls in: 123.450

我正在寻找格式字符串或另一种技巧来摆脱那些不需要的 ,后跟零,但保留有效数字。因此:

I am looking for a formatting string or another trick to get rid of those "unneeded" trailing zeros, but keeping the significant digits. So:

123M.ToString() ==> resuls in: 123
123.00M.ToString() ==> resuls in: 123
123.450M.ToString() ==> resuls in: 123.45

对于我来说,删除新字符串末尾的零不是一个真正的选择,因为那时我必须找出字符串是否包含小数,如果是这样,还必须删除可选的。或,,具体取决于区域性,等等。

Removing the zeros at the end of the new string is not a real option for me, because then I have to find out if the string contains a fraction and if so, also have to remove the optional '.' or ',' depending on the culture, etc.

推荐答案

有几种方法可以实现,但是既然您还是要转换为String对象,我想您可以尝试这样的方法:

There are several ways to do it, but since you are converting to a String object anyway, I suppose you could try something like this:

myDecimalVariable.ToString( G29);

,或者使用上面的代码,假设 123.00M 是您的小数:

or, using your code above, assuming 123.00M is your decimal:

123.00M.ToString( G29) ;

以下是该简洁示例的工作原理的解释:

Here is the explanation of how that concise example works:


带数字的G格式表示要格式化许多有效的
数字。由于29是
可以使用的十进制数字的最高有效位,因此这将有效地截断尾随零而不进行
舍入。

The G format with a number means to format that many significant digits. Because 29 is the most significant digits that a Decimal can have, this will effectively truncate the trailing zeros without rounding.

这篇关于如何在不尾随零的情况下格式化小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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