【问题标题】:getting precision to 5 in C# for decimal data type [duplicate]在 C# 中为十进制数据类型获取精度为 5 [重复]
【发布时间】:2018-04-25 05:07:22
【问题描述】:

我正在潜入 2 个十进制数字,并希望值达到 5 个精度。下面是我的代码。

decimal postiveTotal = 3,totalLenght = 6;
decimal postiveFractionResult = postiveTotal / totalLenght;

我期待 0.50000 但我得到 0.5

【问题讨论】:

  • String.Format("{0:0.00000}", postiveFractionResult ); dotnetfiddle.net/v7oVMe
  • 第一个问题您是否要打印字符串中的值?
  • 你想如何使用它?
  • 据我了解,OP 没有要求进行字符串转换。如果 OP 想要在不将其转换为字符串的情况下获得预期结果怎么办?
  • 您能否解释一下为什么您希望结果为 0.50000?您可以通过将 postiveTotal 初始化为 3.00000m 来获得该结果,但我不明白您为什么希望自动获得 5 位小数。

标签: c#


【解决方案1】:

像十进制这样的C#数字显示类型总是会去掉附加的0——0.5和0.50没有区别。

如果您想正确格式化输出,您需要使用字符串格式标识符:

自定义数字格式标识符:

Console.WriteLine($"{postiveFractionResult:0.00000}");

标准号格式标识符:

Console.WriteLine($"{postiveFractionResult:F5}");

变量赋值:

   // using string interpolation
   string result = $"{postiveFractionResult:0.00000}";
   // using string.format explicite
   string result = string.Format("{0:0.00000}", postiveFractionResult);

你可以找到更多关于字符串格式here的信息。

编辑

正如 Daisy Shipton 所指出的,在声明变量时存在 0.5M 或 0.50M 的差异。对不同声明的小测试表明,额外定义的 0 也通过计算保留:

var result  = 1.25m * 0.5m;         // 6.25M
var result1 = 1.250m * 0.5m;        // 0.6250M
var result2 = 1.250m * 0.50000m;    // 0.62500000M
var result3 = 1.25000m * 0.5m;      // 0.625000M
var result4 = 1.25000m * 0.50000m;  // 0.6250000000M

另请参阅以下so post,其中对此行为进行了解释。遗憾的是,链接已损坏,由于网站当前处于离线状态,我找不到正确的 ECMA 链接。

【讨论】:

  • "0.5 和 0.50 之间没有区别" - 是的,对于十进制。试试decimal x = 0.5m; decimal y = 0.50m; Console.WriteLine(x); Console.WriteLine(y);。您会看到y 中的多余数字已被保留。
  • @DaisyShipton 感谢您的评论!我提到,在使用字段计算时没有真正的区别(至少从结果中的数学逻辑来看)。我已更新我的答案以反映您的评论。
  • 打印Console.WriteLine( postiveFractionResult.ToString("F5")); 的工作方式相同——它是standard numeric fixed point format——而不是使用自定义数字格式。
  • @PatrickArtner 谢谢!更新了我的帖子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-16
  • 1970-01-01
  • 2011-07-31
  • 1970-01-01
  • 1970-01-01
  • 2011-04-03
相关资源
最近更新 更多