S. Dixon
S. Dixon

Reputation: 851

String format double with arbitrary precision, fixed decimal position

I want to write a function that takes in 4 arguments, and prints out a string satisfying the following conditions:

  1. The decimal should be in string position X (where X is constant). That way, when I print a series of such strings, the decimal position always lines up.
  2. In practice, the double has usually up to 5 digits on the left of the decimal place, including the negative sign. and up to 7 digits on the right of the decimal place.
  3. The other fields are left-justified and have fixed column widths.

So far I have been able to deal with 3 of the 4 columns; however, I am having trouble with the decimal argument. I can't seem to figure out how to combine arbitrary precision with a fixed decimal place. Here is what I've got so far:

public String PrintRow(string fieldName, string fieldUnit, double value, string description){ 
    return string.Format(
        " {0,4}.{1,-4}        {2,8:####0.0000####} : {3,-25}\n", 
        fieldName, fieldUnit, value, description);
}

Here are some example outputs that I'd like to be able to make:

 STRT.M            57.4000                 : Start
 STOP.M           485.8000                 : Stop
 STEP.M             0.1524                 : Step
 SMTN.FT         -111.2593615              : Something Cool

What should I do?

Upvotes: 1

Views: 348

Answers (1)

Robert Aguilar
Robert Aguilar

Reputation: 106

This should give you what you want:

public static string PrintRow(string token, string unit, double value, string desc)
{
    // convert the number to a string and separate digits
    // before and after the decimal separator
    string[] tokens = value
        .ToString()
        .Split(new string[] { CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator }, StringSplitOptions.RemoveEmptyEntries);

    // calculate padding based on number of digits
    int lpad = 11 - tokens[0].Length;
    int rpad = 19 - tokens[1].Length;

    // format the number only
    string number = String.Format("{0}{1}.{2}{3}",
        new String(' ', lpad),
        tokens[0],
        tokens[1],
        new string(' ', rpad));

    // construct the whole string
    return string.Format(" {0,-4}.{1,-4}{2}  : {3,-23}\n",
        token, unit, number, desc);
}

Upvotes: 2

Related Questions