【问题标题】:How to convert a double value to string without rounded [duplicate]如何在不四舍五入的情况下将双精度值转换为字符串[重复]
【发布时间】:2015-11-07 14:10:17
【问题描述】:

我有这个变量:

Double dou = 99.99;

我想把它转换成字符串变量,字符串应该是99.9

我可以这样做:

string str = String.Format("{0:0.#}", dou);

但我得到的值是:100 不是99.9

那么我该如何实现呢?

PS:这个问题被标记为重复。是的,他们可能有相同的解决方案(尽管我认为这是一种解决方法),但是从不同的角度来看。

例如,如果有另一个变量:

Double dou2 = 99.9999999;

我想把它转成字符串:99.999999,那我该怎么做呢?像这样:

Math.Truncate(1000000 * value) / 1000000;

但是如果点后面有更多数字怎么办?

【问题讨论】:

标签: c#


【解决方案1】:

你必须截断第二个小数位。

Double dou = 99.99;
double douOneDecimal = System.Math.Truncate (dou * 10) / 10;
string str = String.Format("{0:0.0}", douOneDecimal);

【讨论】:

    【解决方案2】:

    可以使用Floor方法向下取整:

    string str = (Math.Floor(dou * 10.0) / 10.0).ToString("0.0");
    

    0.0 格式表示即使为零也会显示小数,例如99.09 被格式化为99.0 而不是99

    更新:

    如果您想根据输入中的位数动态地执行此操作,那么您首先必须决定如何确定输入中实际有多少位数。

    双精度浮点数不以十进制形式存储,它们以二进制形式存储。这意味着一些你认为只有几位数的数字实际上有很多。您看到的 1.1 数字实际上可能具有 1.099999999999999945634 的值。

    如果您选择使用将其格式化为字符串时显示的位数,那么您只需将其格式化为字符串并删除最后一个数字:

    // format number into a string, make sure it uses period as decimal separator
    string str = dou.ToString(CultureInfo.InvariantCulture);
    // find the decimal separator
    int index = str.IndexOf('.');
    // check if there is a fractional part
    if (index != -1) {
      // check if there is at least two fractional digits
      if (index < str.Length - 2) {
        // remove last digit
        str = str.Substring(0, str.Length - 1);
      } else {
        // remove decimal separator and the fractional digit
        str = str.Substring(0, index);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多