Frage

I need to convert a Double into a String respecting some conditions:

  • I don't want a rounded value
  • Only 3 digits after comma
  • + or - symbol and beginning.
  • (Extra : 0.000 if the double value is 0) (Not the most important)

So, if my Double value is 0.257894214 I want the string to be : +0.257.

I tested a few lines of code :

Double num = 0.257894214;
Double num2 = -0.257894214;
Double num3 = 0;

num.ToString("R")   // 0,257894214
num2.ToString("R")  // -0,257894214
num3.ToString("R")  // 0

String.Format("{0:0.000}",num)      // 0,258
String.Format("{0:0.000}",num2)     // -0,258
String.Format("{0:0.000}",num3)     // 0,000
num.ToString("0.000")               // 0,258
num2.ToString("0.000")              // -0,258
num3.ToString("0.000")              // 0,000

num.ToString("+0.000;-0.000;0.000")             // +0,258
num2.ToString("+0.000;-0.000;0.000")            // -0,258
num3.ToString("+0.000;-0.000;0.000")            // 0,000
String.Format("{0:+0.000;-0.000;0.000}",num)    // +0,258
String.Format("{0:+0.000;-0.000;0.000}",num2)   // -0,258
String.Format("{0:+0.000;-0.000;0.000}",num3)   // 0,000

I feel near the solution but i'm now completely lost!

The last lines are really near what i'm searching for ... but the Double value is rounded ... :(

I hope I have been clear. :) Thanks in advance.

Au revoir !

War es hilfreich?

Lösung

If I've understood you're post, what you're saying is that you want to truncate at the 3rd decimal place rather than round. So you get the values +0.257, -0.257 and 0.000

The following should do that:

First define a function

// truncates to 3 decimal places
static double Truncate(double num)
{
    return Math.Truncate(num * 1000) / 1000.0;
}

Now try

x = String.Format("{0:+0.000;-0.000;0.000}", Truncate(num));
y = String.Format("{0:+0.000;-0.000;0.000}", Truncate(num2));
z = String.Format("{0:+0.000;-0.000;0.000}", Truncate(num3));

This should work for both positive and negative numbers.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top