Skip to content

Instantly share code, notes, and snippets.

@Axemasta
Created January 6, 2026 16:10
Show Gist options
  • Select an option

  • Save Axemasta/353ce4f928168c10f24faeaee4409ae5 to your computer and use it in GitHub Desktop.

Select an option

Save Axemasta/353ce4f928168c10f24faeaee4409ae5 to your computer and use it in GitHub Desktop.
Format strings with percentages testing
using System;
using System.Globalization;
using System.Collections.Generic;
public class Program
{
private static List<string> formatStrings = [
"Doing {0}: {1}%",
"Doing {0}: {1:#0%}",
"Doing {0}: {1:#0}%",
"Doing {0}: {1:P}%"
];
private static Dictionary<string, string> results = new();
private static Random random = new Random(42);
public static void Main()
{
foreach (var formatString in formatStrings)
{
decimal randomPercentage = (decimal)random.NextDouble();
var result = FormatString(formatString, "Something", randomPercentage);
results.TryAdd(formatString, result);
}
foreach (var result in results)
{
Console.WriteLine($"Format string '{result.Key}' yielded output:{Environment.NewLine}{result.Value}");
}
}
private static string FormatString(string formatString, string title, decimal percentage)
{
try
{
return string.Format(CultureInfo.InvariantCulture, formatString, title, percentage);
}
catch (Exception ex)
{
return ex.Message;
}
}
}
@Axemasta
Copy link
Author

Axemasta commented Jan 6, 2026

Script output on dotnetfiddle.net

Format string 'Doing {0}: {1}%' yielded output:
Doing Something: 0.668106465911542%
Format string 'Doing {0}: {1:#0%}' yielded output:
Doing Something: 14%
Format string 'Doing {0}: {1:#0}%' yielded output:
Doing Something: 0%
Format string 'Doing {0}: {1:P}%' yielded output:
Doing Something: 52.28 %%

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment