0

Is it possible to apply multiple formatting simultaneously to a double?

For example, I want something like this

double d = 1234.567;
string format = ? 
// sig digit 4 , digit after decimal 4 , format = combination of G4 and F4 , G4F4?
d.toString(format) => "1235.0000"

Here, "G4" limits the significant digits to 4 and "F4" determines the number of digits after decimal point.

I know it is possible by using 2 separate format

Double.Parse((1234.567).ToString("G4")).ToString("F4") => "1235.0000"

Some more example

//sig digit 3 , digit after decimal 0 , format = combination of G3 and F0
d.toString(format) => "1230"
//sig digit 8 , digit after decimal 8 , format = combination of G8 and F8
d.toString(format) => "1234.56700000"
//sig digit 1 , digit after decimal 1 , format = combination of G1 and F1
d.toString(format) => "1000.0"
4
  • What about this var str = (1234.567m).ToString("0000.0000")? It returns "1234.5670" and returns "0034.5670" for 34.567 Commented Jul 30, 2017 at 12:07
  • 4
    Please provide 5-10 sample inputs and the expected sample outputs for those inputs.
    – mjwills
    Commented Jul 30, 2017 at 12:08
  • 1
    You are conflating two separate concerns here. One is rounding and the other is format strings. To get 1234.567 to output as 1000.0 you should round it then use a format string. To output it as 1234.56700000 you just need a format string.
    – mjwills
    Commented Jul 30, 2017 at 12:32
  • I was curious to combine the "G" format as 1234.567.tostring("G1") can output 1000 (1E+03). Anyway, thanks for the comment, it's not possible in a single format string. Commented Jul 30, 2017 at 12:47

2 Answers 2

0

Your format string doesn't really make any sense. Significant digits can be before or after the decimal point; you're trying to specify two overlapping and contradictory formats simultaneously.

I think you are looking for: ToString("0.0000")

1
  • Thanks, I think it's not possible with single format statement. Commented Jul 30, 2017 at 12:29
0

I think your question is about Standard Numeric Format Strings, then you should follow its specifications, else you will get a FormatException as noted at the end of table:

Any other single character | Unknown specifier | Result: Throws a FormatException at run time.


What about using an extension method like this:

public static string ToString(this double value, int sig)
{
    return double.Parse(value.ToString($"G{sig}")).ToString($"F{sig}");
}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.