c# - 十进制?删除尾随零
问题描述
我正在尝试将其转换decimal? largeValue
为 just569
但是当我使用Truncate
时出现错误“无法将十进制转换为十进制”
这是删除尾随零的正确方法吗?
decimal? Value = 569;
decimal? largeValue = 569.0000M;
decimal? outValue;
outValue = decimal?.Truncate(largeValue);
解决方案
可空值类型有一个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 方法可能会显示尾随零。
你每天学习新的东西!
推荐阅读
- firebase - 有没有办法设置 Firebase 刷新令牌的过期时间?
- python - pytest 失败并显示“错误:找不到文件或目录:和”
- python - Python - 拆分 DataFrame 以制作训练集
- java - 如何从具有任意深度的深度嵌套哈希表中检索值?
- jquery - 使用 jquery 从克隆的输入字段上传多个文件
- ios - Tableview numberOfRowsInSection 返回重复的.count 数字?
- python - 使用外部 CMD 启动程序,检测何时关闭
- python - 将函数应用于 NumPy 数组的唯一值
- api - 端点应该设计多深的资源访问权限
- c# - 如何根据角色(ASP.NET 身份)使用户具有不同的属性