Achieve same results with ToString() as with String.Format - c#

Can't figure out how to implement this task:
I need to format a decimal like this
var formatted = String.Format("{0:G}%", numberOfDecimalType);
So, the result should be number formatted number with trailing % sign.
The problem is that I need to get this result using .ToString() method.
I've tried numberOfDecimalType.ToString("G%") and different other variants but it didn't help
Is it possible?

You can add literal characters by using a custom numeric format string:
var formatted = numberOfDecimalType.ToString(#"#,##0.##\%");
The backslash ensures that % is treated as a literal character rather than a special formatting instruction.
Note, though, that this is not an exact replacement of G, i.e., you might need to adjust the number of #s to accommodate for the required number of decimal places.

You won't be able to append the "%" to the end using a single ToString call; you'll need to format the decimal using ToString and then append the percent sign separately:
var formatted = numberOfDecimalType.ToString("G") + "%";

You could simply append the percent, couldn't you?
formatted = numberOfDecimalType.ToString("G") + "%";

Related

How to use string.Format() to format a hex number surrounded by curly brackets?

Input: uint hex = 0xdeadbeef;
Required output: string result = "{deadbeef}"
First approach: Explicitly add the { and }; this works:
result = "{" + string.Format("{0:x}", hex) + "}"; // -> "{deadbeef}"
Output as decimal rather than hex using escaped curly brackets:
result = string.Format("{{{0}}}", hex); // -> "{3735928559}"
Seems promising, now all we need to do is add the :x hex specifer as per the first approach above:
result = string.Format("{{{0:x}}}", hex); // -> "{x}"
Oh dear, adding the ':x has made it output "{x}" rather than the "{deadbeef}" that I wanted.
So my question is: Must I solve this by explicitly adding the { and } as per the first example, or is there a way to do it using composite formatting and escaping the curly brackets?
Also note that this also affects string interpolation which (after all) is just converted by the compiler into a call to string.Format().
(This may well be duplicate question, but I have been unable to find a duplicate so far...)
edited
See "Escaping Braces" in http://msdn.microsoft.com/en-us/library/txafckwd(v=vs.110).aspx - basically your workaround is a solution.
From there:
The way escaped braces are interpreted can lead to unexpected results.
For example, consider the format item "{{{0:D}}}", which is intended
to display an opening brace, a numeric value formatted as a decimal
number, and a closing brace. However, the format item is actually
interpreted in the following manner:
1.The first two opening braces ("{{") are escaped and yield one opening brace.
2. The next three characters ("{0:") are interpreted as the start of a format item.
3. The next character ("D") would be interpreted as the Decimal standard
numeric format specifier, but the next two escaped braces ("}}") yield
a single brace. Because the resulting string ("D}") is not a standard
numeric format specifier, the resulting string is interpreted as a
custom format string that means display the literal string "D}".
4. The last brace ("}") is interpreted as the end of the format item.
5. The final result that is displayed is the literal string, "{D}". The
numeric value that was to be formatted is not displayed.
and as a solution, adjusted to your example:
uint hex = 0xdeadbeef;
string output = string.Format("{0}{1:x}{2}",
"{", hex, "}");
Console.WriteLine(output);
Closest i got is
string.Format("{{{0:x}\u200B}}",16)
It seems that }}} is interpreted wrong, inserting a zero-width space prevents the first two } being expanded as an escaped } character.
You can use an empty character or add brackets as arguments:
uint hex = 0xdeadbeef;
string result = string.Format("{0}{1:x}{2}", "{", hex, "}");
This will output you {deadbeef} as you wanted.
This happens because to output } in string.Format you have to escape it like this }}.
But when you enter }}} it understands this like }} } and outputs {x}. This is a design bug in C#, when you try to format your output like :x, :N or else.
You can also try
uint hex = 0xdeadbeef;
string result = string.Format("{{ {1:x} }}", hex);
But this will output you { deadbeef } with spaces.
Try this : Use 2 times String.Format Method like this
String result= String.Format("{{{0}}}",String.Format("{0:x}", hex));

How to parse an 0 decimal to String?

Why is it when I'm parsing a decimal (0) ToString my string shows as empty when using the method:
String somthing = someDecimal.ToString("#")
And when I'm using:
String somthing = somDecimal.ToString("0.##")
The string shows up as 0?
When I'm looking at the value in the debug mode in both way it's says they have a "0" in them.
From The "#" Custom Specifier
Note that this specifier never displays a zero that is not a
significant digit, even if zero is the only digit in the string. It
will display zero only if it is a significant digit in the number that
is being displayed.
If you want to display digits after your decimal point, you need to use 0.00 instead of 0.##.
Because pound "#" means convert to symbol if there is a number. 0 is an "empty" number, so it converts to "".
In fact, in second case, you get 0, as you imply to show at least one digit before dot.
This all is by design convention of C# language.
MSDN: the "#" Custom Specifier
The "#" custom format specifier serves as a digit-placeholder symbol.
If the value that is being formatted has a digit in the position where
the "#" symbol appears in the format string, that digit is copied to
the result string. Otherwise, nothing is stored in that position in
the result string. Note that this specifier never displays a zero that
is not a significant digit, even if zero is the only digit in the
string. It will display zero only if it is a significant digit in the
number that is being displayed.
So if the decimal would be 1 instead of 0 it would be diplayed even with ToString("#").
If you want a fixed number of decimals after the decimal point, you need to use
String somthing = somDecimal.ToString("0.00")
In your example you use the # specifier which means 'put here a number if there is a meaningful number'.
It would work if someDecimal is 0.01
decimal somDecimal = 0.01m
String somthing = somDecimal.ToString("0.##");
but not if
decimal somDecimal = 0.01m
String somthing = somDecimal.ToString("0.#");

c# - How do I round a decimal value to 2 decimal places. with , every 1000

So always add a comma and have it to two decimal places, "F" nearly works but can't find the right solution
decimal = 1000.5
test.Text = decimal.ToString("F")
I've also tried:
String.Format("{0:#,###.##}", decimal);
I want to display as the string as 1,000.50
Try:
String.Format("{0:#,###.00}", decimalNumber);
See: Custom Numeric Format Strings
0 - Zero placeholder Replaces the zero with the corresponding digit if
one is present; otherwise, zero appears in the result string. More
information: The "0" Custom Specifier.
It is not going to round the numbers, it is just string formatting.
For culture insensitive formatting do:
String.Format(CultureInfo.InvariantCulture, "{0:#,###.00}", decimalNmber);
String.Format(CultureInfo.InvariantCulture, "{0:0,0.00}", decimal)
For more options see this link.
And here you can test this online.

Can't remove white spaces from a string?

Hi i have a decimal value witch i'm trying to remove the white space when the value is over a thousand.
When a value is returned with over a thousand the number is returned something like "2 000", the white space is causing problems.
I have tried replace and trim and just can't find a way to remove the white spaces.
decimal fee = AdministrationDataManager.AdminMarkupForPriceSelect(price, isProduct, companyId);
string Fee = (fee.ToString("N2"));
string newFee = Fee.Replace(" ", string.Empty);
newFee = newFee.Trim();
return (newFee);
The formatting string "N2" format numbers with thousand separators. If you don't want thousand separators, use "F2" instead.
decimal Fee = 12345678.456M;
Fee.ToString("N2"); // 12,345,678.46 (Only an example)
Fee.ToString("F2"); // 12345678.46 (may also be 12345678,46, depending on culture)
See MSDN for more.
There is really no point to try to replace thousand separators using string.Replace, because it can be different on different computers.
You shouldn't use fee.ToString("N2") if you don't want the thousands separator in the first place. Simply use fee.ToString() to get it in the format you want.

Putting Commas in a Decimal

IF i have the following:
MyString.ValueType = typeof(System.Decimal);
how can i make this have an output of decimals with commas? In other words, instead of seeing 1234.5, i'd like to see 1,234.5
Use:
String output = MyString.ValueType.ToString("N");
The "N" format specifier will put in the thousands separators (,). For details, see Decimal.ToString(string).
Edit:
The above will use your current culture settings, so the thousands separators will depend on the current locale. However, if you want it to always use comma, and period for the decimal separator, you can do:
String output = MyString.ValueType.ToString("N", CultureInfo.InvariantCulture);
That will force it to use the InvariantCulture, which uses comma for thousands and period for decimal separation, which means you'll always see "1,234.5".

Categories

Resources