首页 > 解决方案 > 十进制?删除尾随零

问题描述

我正在尝试将其转换decimal? largeValue为 just569但是当我使用Truncate时出现错误“无法将十进制转换为十进制”

这是删除尾随零的正确方法吗?

decimal? Value = 569;
decimal? largeValue = 569.0000M;
decimal? outValue;
outValue = decimal?.Truncate(largeValue);

标签: c#

解决方案


可空值类型有一个Value保存值的属性(如果有的话)和一个HasValue指示变量不为空的属性(因此,有一个值)。此代码编译并工作:

decimal? value = 569;
decimal? largeValue = 569.0000M;
Debug.Assert(largeValue.HasValue);
Debug.Assert(value == largeValue);
decimal? outValue;
outValue = decimal.Truncate(largeValue.Value);

请注意,调用Truncate不会影响该值(尽管它确实消除了存储在数字的十进制表示中的多余零)。但是,两者都569m代表569.0000m相同的数字。

我已被纠正(@alexeilevenkov)。来自https://docs.microsoft.com/en-us/dotnet/api/system.decimal

缩放因子还保留 Decimal 数字中的任何尾随零。尾随零不会影响算术或比较运算中的 Decimal 数的值。但是,如果应用了适当的格式字符串,ToString 方法可能会显示尾随零。

你每天学习新的东西!


推荐阅读