<mr*********@googlemail.comwrote in message
news:9b**********************************@a1g2000h sb.googlegroups.com...
>I feel a bit ashamed asking this after 6 years of C#, but is there a
format string for significant figures before the decimal place?
e.g.
2,354,856:
1 sf = 2,000,000
2 sf = 2,400,000
3 sf = 2,350,000
{0:G} or g gives me scientific notation, but I'm after the above.
The following doesn't fully answer your question but might help, it's a
customer formatter I've cobbled together based on the code at:
http://msdn.microsoft.com/en-us/libr...tprovider.aspx.
I believe the rounding need to be implemented in the
SFFormatProvider.Format() method to achieve the exact results you're looking
for but this shouldn't be too difficult.
class Program
{
static void Main(string[] args)
{
int val = 2354856;
Console.WriteLine(String.Format(
new SFFormatProvider(), "{0}", val));
Console.WriteLine(String.Format(
new SFFormatProvider(), "{0:1}", val));
Console.WriteLine(String.Format(
new SFFormatProvider(), "{0:2}", val));
Console.WriteLine(String.Format(
new SFFormatProvider(), "{0:3}", val));
}
}
public class SFFormatProvider : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
public string Format(string format, object arg,
IFormatProvider formatProvider)
{
char[] carr = arg.ToString().ToCharArray();
int digits = 1;
if (!String.IsNullOrEmpty(format))
digits = Int32.Parse(format);
for (int i = digits; i < carr.Length; i++)
{
carr[i] = '0';
}
return String.Format("{0:n0}",
Convert.ToInt32(new String(carr)));
}
}
Regards
David