[英]Decimal - truncate trailing zeros
I noticed that .NET has some funky/unintuitive behavior when it comes to decimals and trailing zeros. 我注意到.NET在小数和尾随零时有一些时髦/不直观的行为。
0m == 0.000m //true
0.1m == 0.1000m //true
but 但
(0m).ToString() == (0.000m).ToString() //false
(0.1m).ToString() == (0.1000m).ToString() //false
I know about necessity to comply to the ECMA CLI standard. 我知道必须遵守ECMA CLI标准。 However I would like to know if there is built-in way to truncate the trailing zeros for a decimal value without going through string representation (.ToString("G29") and parse back trick would work, but is neither fast nor elegant solution)? 但是我想知道是否有内置的方法来截断十进制值的尾随零而不通过字符串表示(.ToString(“G29”)和解析后退技巧可行,但既不是快速也不是优雅的解决方案) ?
Any ideas? 有任何想法吗? Thanks a lot. 非常感谢。
Use a format string to specify the output of ToString(): 使用格式字符串指定ToString()的输出:
(0.1m).ToString("0.#") -> "0.1"
(0.10000m).ToString("0.#") -> "0.1"
Use a "0" in the format to specify a digit or a non-significate 0, use "#" to specify a significant digit or suppress aa non-significate 0. 在格式中使用“0”指定数字或非指数0,使用“#”指定有效数字或抑制非有效数字0。
Edit: I assuming here that you are worried about the visual (string) representation of the number - if not, I will remove my answer. 编辑:我在这里假设您担心数字的视觉(字符串)表示 - 如果没有,我将删除我的答案。
I don't like it much, but it works (for some range of values, at least)... 我不喜欢它,但它起作用(至少对某些值而言)......
static decimal Normalize(decimal value)
{
long div = 1;
while(value - decimal.Truncate(value) != 0)
{
div *= 10;
value *= 10;
}
if(div != 1) {
value = (decimal)(long)value / div;
}
return value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.