【问题标题】:How to specify number of digits for a decimal type with .ToString() [duplicate]如何使用 .ToString() 指定十进制类型的位数 [重复]
【发布时间】:2019-11-25 21:36:40
【问题描述】:

当我将值从十进制转换为字符串时,我想指定需要 6 位数字。我有以下代码。

decimal bound = (decimal) field.MaxVal; //trait.MaxVal is a Nullable decimal...
// my debugger shows that bound contains the value 20.0000000000
int numDigits = 6;
string num = numDigits.ToString();

string output = bound.ToString("G" + num);
// output is '20' i expected '20.0000'
return output;

关于我将如何做到这一点的任何想法。

我的重点是在字符串中总共包含 6 个数字,而不是 4 个小数位!

注意:绑定的整数部分可能多于或少于 2 位数字。

【问题讨论】:

标签: c#


【解决方案1】:

【讨论】:

  • 这有帮助,但不幸的是不是我需要的,我想知道我是否可以指定数字的位数。例如。 20.0000,numDigits=4 应该是 20.00。
  • @Kikanye,如果整数部分长于 6 位,您能澄清一下预期的行为吗?你想要像 "F" + Math.Max(num - Math.Floor(Math.Log10(n) + 1), 0);
猜你喜欢
  • 2013-03-29
  • 2012-11-28
  • 2014-10-17
  • 2013-02-20
  • 1970-01-01
  • 2019-05-31
  • 2013-07-03
  • 2018-11-30
  • 2020-07-11
相关资源
最近更新 更多