-6

I have this variable:

Double dou = 99.99;

I want to convert it to a string variable, and the string should be 99.9.

I can do it like this:

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

But the value I got is: 100 which is not 99.9.

So how could I implement that?

PS: This question is marked as duplicated. Yes, they may have the same the solution (although I think that's a workaround), but from different viewpoints.

For example, if there is another variable:

Double dou2 = 99.9999999;

I want to convert it to string: 99.999999, so how should I do? Like this:

Math.Truncate(1000000 * value) / 1000000;

But what if there are more digits after dot?

snowell
  • 89
  • 2
  • 10

2 Answers2

2

You have to truncate the second decimal position.

Double dou = 99.99;
double douOneDecimal = System.Math.Truncate (dou * 10) / 10;
string str = String.Format("{0:0.0}", douOneDecimal);
deramko
  • 2,807
  • 1
  • 18
  • 27
1

You can use the Floor method to round down:

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

The format 0.0 means that it will show the decimal even if it is zero, e.g. 99.09 is formatted as 99.0 rather than 99.

Update:

If you want to do this dynamically depending on the number of digits in the input, then you first have to decide how to determine how many digits there actually are in the input.

Double precision floating point numbers are not stored in decimal form, they are stored in binary form. That means that some numbers that you think have just a few digits actually have a lot. A number that you see as 1.1 might actually have the value 1.099999999999999945634.

If you choose to use the number of digits that is shown when you format it into a string, then you would simply format it into a string and remove the last digit:

// 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);
  }
}
Community
  • 1
  • 1
Guffa
  • 687,336
  • 108
  • 737
  • 1,005