formatting string in C#? - 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#

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

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/

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

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);

String.formate can be used for formating.
Go there if you want examples
http://www.csharp-examples.net/string-format-double/

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.

There is a Format method on String.
String.Format("{0:X}", 10); // prints A (hex 10)
There are several methods to format numbers, date...

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?

Related

How can i create a dynamic string format in C#

I have as input the string format CST-000000 and an integer with value 1
Upon using
string result = string.Format("CST-000000", 1);
the expected result should be CST-000001 instead of CST-000000
How could i create this string format dynamically?
For example
- CST-000 should produce CST-001
- HELLO000 should produce HELLO001
- CUSTOMER0000 should produce CUSTOMER0001
Assuming that:
You receive your format string from somewhere and you can't control what it looks like
Your format string ends with 1 or more zeros
If the format string is e.g. CST-00000 and your value is 123, you want the result to be CST-00123
You can do something like this:
Inspect your format string, and separate out the stuff at the beginning from the zeros at the end. It's easy to do this with Regex, e.g.:
string format = "CST-000000";
// "Zero or more of anything, followed by one or more zeros at the end of the string"
var match = Regex.Match(format, "(.*?)(0+)$");
if (!match.Success)
{
throw new ArgumentException("Format must end with one or more zeros");
}
string prefix = match.Groups[1].Value; // E.g. CST-
string zeros = match.Groups[2].Value; // E.g. 000000
Once you have these, note the "Zero placeholder" in this list of custom numeric format strings -- you can write e.g. 123.ToString("0000") and the output will be 0123. This lets you finish off with:
int value = 123;
string result = prefix + value.ToString(zeros);
See it on dotnetfiddle
String.Format requires a placeholder {n} with a zero-based argument number. You can also add it a format {n:format}.
string result = String.Format("CST-{0:000000}", 1);
You can also use String interpolation
string result = $"CST-{1:000000}"
The difference is that instead of a placeholder you specify the value directly (or as an expression). Instead of the Custom numeric format string, you can also use the Standard numeric format string d6: $"CST-{1:d6}"
If you want to change the format template dynamically, String.Format will work better, as you can specify the format and the value as separate arguments.
(Example assumes an enum FormatKind and C# >= 8.0)
int value = 1;
string format = formatKind switch {
FormatKind.CstSmall => "CST-{0:d3}",
FormatKind.CstLarge => "CST-{0:d6}",
FormatKind.Hello => "HELLO{0:d3}",
FormatEnum.Customer => "CUSTOMER{0:d4}"
};
string result = String.Format(format, value);
Also note that the value to be formatted must be of a numeric type. Strings cannot be formatted.
See also: Composite formatting
It seems .toString("CST-000"), .toString("HELLO000") and so on, does the trick.
ToString and String.Format can do much more than use predefined formats.
For example :
string result = string.Format("CST-{0:000000}", 1);
string result = 1.ToString("CST-000000");
Should both do what you want.
(Of course you could replace "1" by any variable, even a decimal one).

Format numeric string with comma separator for indian numbering system

I have a number value in string as
string strNum = "12345678.90";
I want to format it with comma separator using regex in String.Format()
On using "{0:n0}" format in
String.Format("{0:n0}", Convert.ToDouble(strNum));
it is giving me output as "12,345,679"
Instead of this i want output as "1,23,45,678.90". After thousand's place i want comma separator after 2 digits each for lakhs, crores and so on
How can this be achieved?
var s = String.Format(new CultureInfo( "en-IN", false ), "{0:n}", Convert.ToDouble("12345678.90"));
For such a typical way I would write a specialized function that transforms a number into the string you propose.
I even would suggest to make the item a class, having the value represented as float or by different items like lakhs, crores etc.
And then make a ToString method to output it the way you want.
Example (not tested):
class SpecialNumber
{
int _lakhs;
int _crores;
int _another_unit;
int _rest;
public SpecialNumber(int lakhs, int crores, int another_unit, int rest)
{
_lakhs = lakhs;
_crores = crores;
_another_unit = another_unit;
_rest = rest;
}
public string ToString()
{
// Check for exact formatting.
return String.Format("{0:2},{1:2},{2:3}.{0:2}",
_laksh, _crores, _another_unit, _rest);
}
My best bet would be to use the String.Format along with '#' as such:
String.Format(0:##,##,##,##,##,###.##)
The '#' is a digit placeholder and will not show a zero (or anything else) if the number is not large enough.
See MSDN custom numeric format strings for further details.
you seem to format according to hindi culture.
so set your culture, or provide the culture to String.Format, like
String.Format(CultureInfo.GetCultureInfo( "<yourculture>" ), "{0:n}", Convert.ToDouble(strNum));
With this code you can change an amount string to Indian standard comma separated value; use culture "hi-IN" and the format "{0:#,0.00}"
here strNum is my string value amount.
string.Format( System.Globalization.CultureInfo.CreateSpecificCulture("hi-IN"), "{0:#,0.00}", Convert.ToDouble(strNum)

C# - can I parse back text that have already formatted to currency?

this is function to format text that contains numbers only into $ currency
private String GLOBALIZE_TEXT(String originalText)
{
decimal parsed;
CultureInfo myCultureInfo;
string formattedText = "";
//use try catch to prevent larger inputs
try
{
parsed = decimal.Parse(originalText, CultureInfo.InvariantCulture);
myCultureInfo = new CultureInfo("$");
formattedText = string.Format(myCultureInfo, "{0:c}", parsed);
}
catch (Exception ignorethis)
{
}
return formattedText;
}
now in usage:
String myString = "3821";
myString = GLOBALIZE_TEXT(myString);
//now my String becomes "$3,821.00"
question is, can I parse back that "$3,821.00" to "3821" again?
I need to parse it back so I can use it as an integer where "3821" can be converted by Convert.ToInt32("3821").
or maybe that parsed String can also be converted directly to string?
Please let me know your opinion.
You can try:
double.Parse(myString, NumberStyles.Currency);
More information on the NumberStyles enum can be found on MSDN here and more information on this specific double.Parse method can be found on MSDN here.
Maybe it's best to ask why you need to do this? You should always try and store a value in it's native format. If you need to do it from a captured or imported string then I would go the route of using a regular expression to remove it.
Regular expression to remove any currency symbol from a string?

parsing a string into int/long using custom format strings

In C#.Net, here's a simple example of how to format numbers into strings using custom format strings:
(example taken from: http://www.csharp-examples.net/string-format-int/)
String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456"
String.Format("{0:##-####-####}", 8958712551); // "89-5871-2551"
Is there a way to convert this formatted string back into a long/integer ? Is there someway to do this :
long PhoneNumber = Int32.Parse("89-5871-2551", "{0:##-####-####}");
I saw that DateTime has a method ParseExact which can do this work well. But I did not see any such thing for int/long/decimal/double.
You can regex out all of the non numeric numbers, and what you're left with is a string of numbers that you can parse.
var myPhoneNumber = "89-5871-2551";
var strippedPhoneNumber = Regex.Replace(myPhoneNumber, #"[^\d]", "");
int intRepresentation;
if (Int32.TryParse(strippedPhoneNumber, out intRepresentation))
{
// It was assigned, intRepresentation = 8958712551
// now you can use intRepresentation.
} else {
// It was not assigned, intRepresentation is still null.
}
Well, you can always do
long PhoneNumber = Int32.Parse("89-5871-2551".
Replace(new char[]{'-','+',whatever..}).Trim());
By the way, considering that you're parsing a string received from some IO, I would suggest to use more secure (in terms of conversion) Int32.TryParse method.
The way like you described doesn't actually exist.
Just Regex out all of the non-numeric characters, then parse that string.

Formatting values

Hi i have a int example as 3 i need to format it as 003 . is the only way is convert to a string and concat and convert back ?
I guess this is what you want:
int n = 3;
string formatted = n.ToString("000");
Alternatively:
string formatted = String.Format("{0:000}", n);
More info here.
You can apply the .ToString("000"); method.
Debug.WriteLine(3.ToString("000"));
You can parse the resulting string value by using int.Parse or int.TryParse:
Debug.WriteLine(int.Parse("003"));
See Custom Numeric Format Strings
If it's an int object, the leading zeros will always be removed, regardless if you convert it to a string and back.
use the pad functionint i = 1;
i.ToString().PadLeft(3, '0');

Categories