Format the number to always have a sign and decimal separator

I want to format any number (integer or real) in a string representation, which always has a sign (positive or negative) and decimal separator , but without trailing zeros.

Some examples:

3.14 => +3.14 12.00 => +12. -78.4 => -78.4 -3.00 => -3. 

Is this possible with one of the default implementations of ToString() , or do I need to write this myself?

+5
source share
3 answers

Try something like this:

 double x = -12.43; string xStr = x.ToString("+0.#####;-0.#####"); 

But that would not help display the final decimal point. You can handle such situations using this method:

 public static string MyToString(double x) { return x == Math.Floor(x) ? x.ToString("+0;-0;0") + CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator : x.ToString("+0.####;-0.####"); } 
+7
source

You can try the following:

 string myFormatedString = number.ToString("+#;-#"); 
0
source

The format string you want to use is

 ToString("N", CultureInfo.InvariantCulture) // Displays -12,445.68 

See here for additional options for format strings.

0
source

Source: https://habr.com/ru/post/1202073/


All Articles