如何将double值转换为没有舍入的字符串

时间:2015-08-14 10:35:21

标签: c#

我有这个变量:

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;

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

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

您可以使用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);
  }
}