我尝试将一个十进制值格式化(截断)为小数点后4位。例如,我想转换像这样的十进制数字
31.818181818181818181818181818M or 31.818181818181818181M or 31.81818M
至
31.8181
(未四舍五入到31.8182)并将其存储到一个可为null的十进制变量中。我尝试过在不舍入.net的情况下使用十进制格式,并在C#中的某个数字处停止舍入但可为零的小数没有运气。
这是代码
private decimal? ReturnNullableDecimal(decimal? initValue)
{
//e.g. initValue = 35M;
initValue = 35M; //just to debug;
decimal? outputValue = null;
if (initValue != null)
outputValue = initValue / (decimal)1.10;
//now outputValue is 31.818181818181818181818181818M
outputValue = Convert.ToDecimal(string.Format("{0:0.0000}", outputValue)); // <- this should be 31.8181 but gives 31.8182
return outputValue;
}
有人能帮忙吗?
任何decimal
都可以隐式转换为decimal?
,因此与任何其他截断示例中的代码相同。如果您的输入也是decimal?
,则必须在那里检查null。
private decimal? ReturnNullableDecimal(decimal? initValue)
{
if (initValue.HasValue)
return Math.Truncate(10000 * initValue.Value) / 10000;
else
return null;
}
根据接受的答案,我创建了一个扩展
namespace your.namespace.Extensions
{
public static class NullableDecimalExtension
{
public static decimal? FormatWithNoRoundingDecimalPlaces(this decimal? initValue, int decimalPlaces)
{
if (decimalPlaces < 0)
{
throw new ArgumentException("Invalid number. DecimalPlaces must be greater than Zero");
}
if (initValue.HasValue)
return (decimal?)(Math.Truncate(Math.Pow(10, decimalPlaces) * (double)initValue.Value) / Math.Pow(10, decimalPlaces));
else
return null;
}
}
}
用法:添加使用您的.namespace.Extensions;至类
然后在调用方法中可以直接调用
例如
initValue = 35M;
decimal? outputValue = (initValue / (decimal)1.10).FormatWithNoRoundingDecimalPlaces(4);
//now the outputValue = 31.8181
如果我们需要得到2个小数位,只需使用.FormatWithNoRoundingDecimalPlaces(2);