One significant figure in C#

M

mrshrinkray

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
 
D

Dave Shooter

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/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 = '0';
}
return String.Format("{0:n0}",
Convert.ToInt32(new String(carr)));
}
}

Regards
David
 
A

Arne Vajhøj

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.

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top