Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

One significant figure in C#

1 view
Skip to first unread message

mrshr...@googlemail.com

unread,
May 15, 2008, 8:30:35 AM5/15/08
to
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

unread,
May 15, 2008, 11:28:06 AM5/15/08
to
<mrshr...@googlemail.com> wrote in message
news:9b2430fc-810e-4d39...@a1g2000hsb.googlegroups.com...

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


Arne Vajhøj

unread,
May 15, 2008, 11:03:50 PM5/15/08
to

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

0 new messages