.NET Framework - One significant figure in C#

Asked By mrshrinkra on 16-May-08 06:17 AM
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.

Thanks




Dave Shooter replied on 15-May-08 11:28 AM
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/library/system.iformatprovider.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
arn replied on 15-May-08 11:03 PM
I don't think so.

You will need to code it yourself.

One way:

public static string SpecialFormat(int v, int sf)
{
int k = (int)Math.Pow(10, (int)(Math.Log10(v) + 1 - sf));
int v2 = ((v + k/2) / k) * k;
return v2.ToString("0,0");
}

(the calculation of k can be optimized if speed is critical)

Arne