2

I saw this post: How to Conditionally Format a String in .Net?

The first part of the question points to the ability to use conditional formats. How is this done?

In my case, I want to do for instance 100,000 as $100k, and 1,000,000 as $1m. I want to be able to do it with just the FormatString in markup (Silverlight). This is a case where I cant use a value converter (it's inside a style).

Is this possible?

Community
  • 1
  • 1
Roger
  • 2,063
  • 4
  • 32
  • 65
  • You need to code it yourself. Check out: http://stackoverflow.com/questions/2134161/format-number-like-stackoverflow-rounded-to-thousands-with-k-suffix – Mikael Svenson Dec 31 '10 at 22:34
  • what does this refer to in that post I linked to? Int32 i = 0; i.ToString("$#,##0.00;($#,##0.00);Zero"); – Roger Dec 31 '10 at 22:50

1 Answers1

4

You can implement your own IFormatProvider and define ie. custom and pass that when calling String.Format() or ToString().

Example of this can be found here http://msdn.microsoft.com/en-us/library/system.iformatprovider.aspx or here http://www.codeproject.com/KB/cs/custstrformat.aspx.

public class StringFormatInfo : IFormatProvider, ICustomFormatter
{
   ...
}

return number.ToString("{0:custom}", new StringFormatInfo());
Pauli Østerø
  • 6,878
  • 2
  • 31
  • 48
  • i've used it alot myself... its a clean nice api instead of using all kinds of helper methods. – Pauli Østerø Dec 31 '10 at 23:22
  • I don't think this is an option for me because I am using a template binding. I need this inside a style that is applied to the label on the axis of a chart (Silverlight Toolkit). I'll give it a try. – Roger Jan 01 '11 at 00:07
  • There is an article here about how to use custom IFormatProvider's when databinding in WPF http://timheuer.com/blog/archive/2008/07/30/format-data-in-silverlight-databinding-valueconverter.aspx – Pauli Østerø Jan 01 '11 at 00:12