如何格式化小数点后面不跟零的 [英] How to format a decimal without trailing zero's

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

问题描述

我刚刚得知一个小数莫名其妙地记得零的是需要多少trailaing存储号码。与其他词:它会记住分数的大小

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



我要寻找一个格式化字符串或其他TRIC摆脱那些不必要的尾随零的,但保持显著数字。所以:

I am looking for a formatting string or another tric to get rid of those "unneeded" trailing zero's, 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 zero's 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天全站免登陆