C# String formatter - c#

i want to format a string. Assume there is:
string unformatedString="004897582515"
string stringFormater="{0:00#-###-###-####}"
After formatting:
string result = String.Format(stringFormater, Int64.Parse(unformatedString));
the result is: 000-044-788-9556
I'd like to know why? Because after parsing unformatedString into Int64 I am getting 4897582515 value as integer, but after formatting it there are always additional zeros(it's based on count of zeros in the beginning of unformatedString).

The simple reason 004897582515 is turning into 000-0xx-xxx-xxx with the format specifier "{0:00#-###-###-####}" is because of the 0's at the beginning
Custom numeric format strings
Format specifiers
0 : Zero placeholder
Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.
Maybe you want "{0:###-###-###-####}"
Format specifiers
# : Digit placeholder
Replaces the # symbol with the corresponding digit if one is present; otherwise, no digit appears in the result string.
Which in worst case will result in "-xxx-xxx-xxxx"
However, you could hack in a TrimStart('-')
Console.WriteLine(string.Format("{0:###-###-###-####}", 004897582515).TrimStart('-'));
Which will remove any leading dash
Output
489-758-2515
Full Demo Here

Related

String.Format for Phonenumber leading with zeros

Hi I just want to ask about how can i add padding on string.Format so that when I show it , the mask is applied with leading zeros
Heres my c# code
Model.Phone = String.Format("{0:(###) ###-####}", double.Parse(#e.Phone));
Expected result should be
(012) 345-6789
But the results I am getting is
(12) 345-6789
and the leading zero is missing, Hope someone can help me in this problem , Thanks
You would use 000 instead of ###, read more about format in MSDN article Custom Numeric Format Strings
String.Format("{0:(000) ###-####}", double.Parse(#e.Phone));
Format specifier "0"
Replaces the zero with the corresponding digit if one is present;
otherwise, zero appears in the result string.
Format specifier "#"
Replaces the "#" symbol with the corresponding digit if one is
present; otherwise, no digit appears in the result string.

String with suffix fails parsing

When ever one passes string with suffix parsing to decimal fails.
decimal testValue;
decimal.TryParse("5M", NumberStyles.Number, CultureInfo.CurrentCulture, out testValue)
Following parse will return false.
Why does TryParse fail when you pass in a string with a suffix?
Because Decimal.TryParse does not support it.
Depending on the value of style, the s parameter may include the following elements:
[ws][$][sign][digits,]digits[.fractional-digits][e[sign]digits][ws]
Elements in square brackets ([ and ]) are optional. The following table describes each element.
ws: Optional white space. White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag. It can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag.
$: A culture-specific currency symbol. Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern or NumberFormatInfo.CurrencyPositivePattern properties of the NumberFormatInfo object returned by the IFormatProvider.GetFormat method of the provider parameter. The currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.
sign: An optional sign.
digits: A sequence of digits ranging from 0 to 9.
.: A culture-specific decimal point symbol.
fractional-digits: A sequence of digits ranging from 0 to 9.
Because there is no way to parse your string without removing M part. And none of NumberStyles have such a functionality.
I can suggest to Replace your M with empty string but that would be only solve for your case, it won't be a general solution.
decimal testValue;
decimal.TryParse("5M".Replace("M", ""), NumberStyles.Number,
CultureInfo.CurrentCulture, out testValue);
A real-type-suffix specifies number types. It teaches to C# compiler what a numeric literal type considered as. In a string, it means nothing. It is just an another character.

0.0.ToString(".####") returns empty string

Why 0.0.ToString(".####") returns empty string but not 0? What format string should I use for proper output?
To always show the digit for the 1s position, then you need to specify a zero in the string format specifier for that digit. See the following:
// outputs "0"
0.0.ToString("0.####")
If you want to show extra decimal places, even if they are zero, then you can also use zeros to do that:
// outputs "5.1000"
(5.1).ToString("0.0000")
For more information see:
Custom Numeric Format Strings
If you want to show only the 1s position for the number zero.. then do this:
String text = (number == 0) ? "0" : number.ToString(".####");
Think about what you're asking - you ask for no required digits before the decimal point and up to 4 optional significant digits after the decimal point.
Since 0.0 has no significant digits before or after the decimal, it returns nothing.
To give you the proper format string we need the expected output in each of the following cases:
A number >= 1
A number between 0 and 1 (exclusive)
0
Note that you can use section separators to explicitly say how you want to format positive numbers, negative numbers, and 0:
0.0.ToString(".####;-.####;0") // returns "0"
The nice thing about using section separators (versus explicitly checking for 0) is that it will use the "0" format specifier if the formatted string would be equivalent to 0.
For example,
(-0.0000001).ToString(".####;-.####;0")
will return "0" since the small negative number will be rounded to four decimals based on your format specification.

How do I format a number as a string, so that zero is replaced by the empty string

I need for this to work in a single format statement and to work for both ints and decimals:
For example:
int myInt=0;
decimal myDecimal=0.0m;
// ... Some other code
string formattedResult1=String.Format("{0}",myInt);
string formattedResult2=String.Format("{0}",myDecimal);
The expected results are:
"" (i.e., string.Empty) if the item to be formatted is zero
and a numeric value (e.g., "123.456" for the decimal version) if it isn't.
I need for this to occur exclusively as a result of the format specification in the format string.
This should do:
string formattedResult1 = string.Format("{0:0.######;-0.######;\"\"}", myInt);
The colon introduces a numeric format string. The numeric format string is divided into 3 parts with semicolons: part 1 is for positive numbers, part 2 for negative numbers, and part 3 for zeros. To define a blank string you need to delimit it with double quotes otherwise it doesn't like it.
See MSDN for the full syntax.
based from the accepted answer above i have done the same thing in microsoft "report builder"
this worked for me (shows 2 decimal places, blank for zero) :
,##0.00;-#,##0.00;""

String formatting for decimal places and thousands

I would like to represent the number 2.3421 as 2.34 but my current formatting shows it as 02.34
If I had the number 1342.323 I would want to show this as 1,342.32
If I had 0.23 this would be shown as 0.23.
What do I change my format string to achieve this? I have:
"{0:0,0.00}"
Use # where a number is optional instead of 0:
"{0:#,0.00}"
See Custom Numeric Format Strings on MSDN:
"#" | Digit placeholder
Replaces the pound sign with the corresponding digit if one is present; otherwise, no digit appears in the result string.
Try this:
{0:#,##0.00}
1342.323 should then be 1,342.32

Categories