SRA
SRA

Reputation: 1691

formatting string in C#?

I've a predefined string format. For instance '>>>,>>>,>>9.99' this means that the system should display string in this '500,000,000.10'. The format can change based on the users using it. How can I write a common function to display stings on the given format passing the input value and the format as the parameter using C#

Upvotes: 0

Views: 295

Answers (8)

Vadim Sentiaev
Vadim Sentiaev

Reputation: 761

For example:

string format = "{0:000,000,000.00}";
string val = 12.3456;
Console.WriteLine(string.Format(format, value)); // it prints "000,000,123.23"

You can read more about formating values here http://www.csharp-examples.net/string-format-double/

Upvotes: 1

Theun Arbeider
Theun Arbeider

Reputation: 5409

I dont seem to understand how you can make 500,000,000.10 from >>>,>>>,>>9.99' but I believe the answer would be

But I assume something you are looking for is: string.Format("500,000,00{0:0.##}", 9.9915)

You can then make a method like

Public string GetString(string Format, object value)
{
     return string.Format(Format, value);
}

Something like this?

Upvotes: 0

BrunoLM
BrunoLM

Reputation: 100312

There is a Format method on String.

String.Format("{0:X}", 10); // prints A (hex 10)

There are several methods to format numbers, date...

Upvotes: 0

Hans Olsson
Hans Olsson

Reputation: 55001

I think the following might work:

String result = String.Format(fmt.Replace('>', '#').Replace('9', '0'), inpString);

fmt being the format you want to use and inpString being the string entered by the user.

Just replace the > with # and the 9 with 0 and it'll be a valid .Net formatstring.

Upvotes: 0

Ali Murtaza
Ali Murtaza

Reputation: 109

String.formate can be used for formating.

Go there if you want examples http://www.csharp-examples.net/string-format-double/

Upvotes: 0

WraithNath
WraithNath

Reputation: 18013

private string sDecimalFormat = "0.00";

decimal d = 120M;

txtText.Text = d.ToString(sDecimalFormat);

You could then have a setting for decimal format eg:

txtText.Text = d.ToString(Settings.DecimalFormat);

Upvotes: 0

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120917

You can use the ToString method with a standard or custom format string

Upvotes: 1

Pabuc
Pabuc

Reputation: 5638

decimal value = 1.2345; 
string rounded = value.ToString("d2");

Upvotes: 0

Related Questions