I wanted to
- have space as a thousand separator,
- have up to two decimals and
- optionally be negative.
This code solves it:
var regex = new Regex(@"(^|(?<=-))\s*");
var format = "### ### ### ### ##0.##";
decimal number = 123456789.54m;
var str = regex.Replace(number.ToString(format), ""); // str = "123 456 789.54"
Here are examples of how this behaves for various numbers:
regex.Replace(0m.ToString(format), "")
"0"
regex.Replace(123m.ToString(format), "")
"123"
regex.Replace(123456789m.ToString(format), "")
"123 456 789"
regex.Replace(123456789.1m.ToString(format), "")
"123 456 789.1"
regex.Replace(123456789.12m.ToString(format), "")
"123 456 789.12"
regex.Replace(123456789.1234m.ToString(format), "")
"123 456 789.12"
regex.Replace((-123456789.1234m).ToString(format), "")
"-123 456 789.12"
regex.Replace((-1234m).ToString(format), "")
"-1 234"
regex.Replace((-1m).ToString(format), "")
"-1"