十进制格式的ToString这使至少1位,无上限 [英] decimal ToString formatting which gives at least 1 digit, no upper limit
本文介绍了十进制格式的ToString这使至少1位,无上限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何格式化C#中的十进制
至少有一个数字小数点后,但如果指定了不止1位,小数点后固定的上限:
5 - > 5.0
5.1 - > 5.1
5.122 - > 5.122
10.235544545 - > 10.235544545
解决方案
使用 的ToString(0.0 ###########################)
。
一些注意事项:,
- 有27个
#
在里面,为的十进制
可容纳precision多达28位小数的结构。 - 的
0
定制符的会造成位,即使该值为0。 - 的
#
自定义说明仅显示一个值,如果数字是零,所有的数字到数字的左右/(取决于你是什么侧小数点)均为零。 - 您将需要插入尽可能多的
#
后的第一个0
小数点右边,以适应所有值的长度,你会传递到的ToString
,如果你只会有precision小数点后10位,那么你就需要9#
(因为你有小数点后第一位被处理的权利0
)
有关详细信息,请参见标题为自定义数字格式字符串 。
How to format a decimal
in C# with at least one digit after the decimal point, but not a fixed upper limit if specified more than 1 digit after the decimal point:
5 -> "5.0"
5.1 -> "5.1"
5.122 -> "5.122"
10.235544545 -> "10.235544545"
解决方案
Use ToString("0.0###########################")
.
Some notes:,
- There are 27
#
s in there, as thedecimal
structure can accommodate precision up to 28 decimal places. - The
0
custom specifier will cause a digit to always be displayed, even if the value is 0. - The
#
custom specifier only displays a value if the digit is zero and all of the digits to the right/left of that digit (depending on what side of the decimal point you are on) are zero. - You will need to insert as many
#
after the first0
to the right of the decimal point to accommodate the length of all the values you will pass toToString
, if you will only have precision to 10 decimal places, then you need nine#
(since you have the first decimal place to the right handled by0
)
For more information, see the section of MSDN titled "Custom Numeric Format Strings".
这篇关于十进制格式的ToString这使至少1位,无上限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文