fedab
fedab

Reputation: 989

Format custom numeric string with fixed character count

I need to convert any number in a fixed format with a fixed amount of characters. Means 1500 and -1.5 or 0.025 need to have the same length. I also have to give the format in this form: Format = "{???}";

When i type Format = "{0000}"; i can limit 1500 to "1500", but -1.5 -> "-0001.5" means i have too much numbers after the point.

Negative sign place can be done with Format = "{ 0.0;-0.0; 0.0}".

How can i fix the count of the numbers for different numbers?

The length of the string doesn't matter, the most important is the equal length.

Examples:

1500 ->    " 1500.000" or "     1500"
-1500 ->   "-1500.000" or "-    1500" or "    -1500"
1.5  ->    "    1.500" or "      1.5"
-0.25->    "   -0.250" or "-    0.25"
0.00005 -> "    0.000" or "        0"
150000->   " 150000.0" or "   150000"
15000000   " 15000000"

Edit:

I want to Format an y-Axis of a Chart. I can't use something like value.ToString("???") i need to use chartArea.AxisY.LabelStyle.Format = "{???}";

Upvotes: 1

Views: 932

Answers (3)

BRAHIM Kamel
BRAHIM Kamel

Reputation: 13755

you cannot achieve this by a simple format function

   string result = string.Empty;

        var array = dec.ToString().Split('.');
        if (dec > 0)
        {

            result = array[0].PadLeft(9).Remove(0, 9);


            if (array.Count() > 1)
            {
                result += '.' + array[1].PadRight(3).Remove(3);
            }
        }
        else
        {

            result = "-"+array[0].PadLeft(9).Remove(0, 9);
            if (array.Count() > 1)
            {
                result += '.' + array[1].PadRight(3).Remove(3);
            }

        }

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Why don't use formatting? "F3" forces 3 digits after decimal point and PadLeft ensures the overall length

  Double value = 1500.0;
  // 3 digits after decimal point, 9 characters length
  String result = value.ToString("F3").PadLeft(9, ' ');

         0 ->     0.000
    1500.0 ->  1500.000
   -1500.0 -> -1500.000
     -0.25 ->    -0.250

Another (similar) possibility is String.Format:

  Double value = 1500.0;
  // Put value at place {0} with format "F4" aligned to right up to 9 symbols
  String result = String.Format("{0:9,F4}", value);

Upvotes: 1

zey
zey

Reputation: 6105

Try it > result = Math.Round(yourValue, 3);
Check full reference here !

Upvotes: 0

Related Questions