Ok time for the 2nd dumb question of the day that I should probably already know the answer too..

I have string.Format(" {0, -22} | {1, 5} of {2, -5} | {3, 5}% | where {3} is a double that is being used for a percentage.

The longest allowed format is 5 characters so capable of support something like 99.99

I currently use string.Format("{0:#.00}", x) for the number going into there which works fine for say 64.29

However for other numbers it doesn't display cleanly.

I want to be able to have like:
100%
90%
90.8%
80.70%
1%
1.5%

So basically looking for a more flexible formatting pattern to put instead of {0:#.00}

Dani AI

Generated

Brief recap and what actually fixed it: and pointed out that a custom numeric format using digit placeholders is the right approach, and marked it solved. The important bit is choosing whether you want to (a) always show two decimals, (b) show up to two decimals and drop trailing zeros, or (c) treat the value as a fraction and let the percent format do the math. The examples in the thread (100%, 90%, 90.8%, 80.70%, 1%, 1.5%) can be produced by a small set of formatting choices.

Use the zero placeholder to force digits and the pound/hash placeholder to suppress non-significant digits. For example, use a format that forces a leading zero for values under 1 but allows up to two fraction digits when present, or use a fixed two-decimal format when you need the trailing zero (80.70). The custom-format rules (what 0 and # do, decimal separator behavior, rounding) are documented by Microsoft. (learn.microsoft.com)

If your input is a fraction (0.9 for 90%), use the standard percent format which multiplies by 100 and appends the percent symbol for you; the precision specifier controls how many fractional digits appear (no extra manual “%” needed in that case). That is often simpler and safer than manually appending “%”. (learn.microsoft.com)

Practical notes: keep alignment in mind — a composite-format width applies to the formatted number only, not to a percent sign you append afterwards; include the percent sign in the format (or adjust with PadLeft/PadRight) if you need the sign counted in the column width. Also be explicit about culture if you must force a dot decimal (use CultureInfo.InvariantCulture with ToString).

Recommended Answers

All 4 Replies

I think you're looking for:

string.Format("{0:#.##}", x)

Docs

Solved

Have you tried:

String.Format("{0:#.##}", x)

I hadn't tin and it was the solution, Prit beat you too it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.