signed numbers + or - [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to force a sign when formatting an Int in c#
Format number with + and - sign
I would like to sign numbers when there are positive or negative (c#):
text = cname + " " + String.Format("{0:0.#}", move) + "% , \n " + text;
I want for positive numbers a format like "+2.5%".
Any ideas?

Check on MSDN : Format Number To Display
string MyString = number.ToString("+#;-#;0");
; - Section separator - Defines sections with separate format strings for positive, negative, and zero numbers.

Related

How to specify number of digits for a decimal type with .ToString() [duplicate]

This question already has answers here:
How to format floating point value with fix number of digits?
(3 answers)
How do I format a Decimal to a programatically controlled number of decimals in c#?
(5 answers)
Closed 3 years ago.
I would like to specify that I want 6 digits when I convert a value from a decimal to a string. I have the following code.
decimal bound = (decimal) field.MaxVal; //trait.MaxVal is a Nullable decimal...
// my debugger shows that bound contains the value 20.0000000000
int numDigits = 6;
string num = numDigits.ToString();
string output = bound.ToString("G" + num);
// output is '20' i expected '20.0000'
return output;
Any ideas on how I would do this.
I am focused on getting a total of 6 numbers in my string as opposed to 4 decimal places!
NOTE: bound will may have more or less than 2 digits in the whole number part.
string output = bound.ToString("F" + num);
https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings?redirectedfrom=MSDN#FFormatString
F stands for fixed-point.

Formatting Phone Number by adding zeros to the left [duplicate]

This question already has answers here:
C# convert int to string with padding zeros?
(15 answers)
Closed 6 years ago.
I have phone numbers like this :
452341
12
45789632
Is there a way i can format them like this way :
00452341
00000012
45789632
You cam use Padding:
Number.PadLeft(length, '0');
For example:
string num = "1234";
num.PadLeft(10, '0');
The result will be 0000001234
ToString("D8")
Here - MSDN - Decimal ("D") Format Specifier
NOTE:
PadLeft(length, '0'); does not work for negative numbers
Ex: (-1).Padleft(5, '0') --> 000-1
Use format with leading zeroes (Example for 8 symbols in number):
452341.ToString("D8");
if you have already strign use solution of Ashkan:
"452341".PadLeft(8, '0');

String Format wrong format for % [duplicate]

This question already has answers here:
How can I use a percent % in FormatString without it multiplying by 100?
(4 answers)
Closed 9 years ago.
I want to format an Axis in a Chart. For this i have following line:
chart.ChartAreas[series.Name].AxisY.LabelStyle.Format =
"{0.# " + unit + ";-0.# " + unit + ";0 " + unit + "}";
Example for unit = "Joule": Format = "{0.# Joule;-0.# Joule;0 Joule"}
It brings me a good result (e.g. 1.5 -> "1.5 Joule", -1.4 -> "-1.4 Joule").
But if unit = "%" the values are multiplicated by 100. Means 5 -> "500%", 1.3 -> "130%"... and that's wrong. Also some inputs like " %" (with a variable spaces in the string), "_%", "‰" multiplicate the numbers.
Is there a way to show a percent number and prevent this effect?
Please note that i have to use the Format in this form Format = "???"; and i don't want to manipulate any DataPoints (like every DataPoint / 100).
You can put literal characters in quotes to avoid them being interpreted as format codes:
chart.ChartAreas[series.Name].AxisY.LabelStyle.Format =
"{0.# '" + unit + "';-0.# '" + unit + "';0 '" + unit + "'}";
Escape the percentage sign.
unit = #"\%";
or
unit = "\\%;

Format decimal value to string with leading spaces

How do I format a decimal value to a string with a single digit after the comma/dot and leading spaces for values less than 100?
For example, a decimal value of 12.3456 should be output as " 12.3" with single leading space. 10.011 would be " 10.0". 123.123 is "123.1"
I'm looking for a solution, that works with standard/custom string formatting, i.e.
decimal value = 12.345456;
Console.Write("{0:magic}", value); // 'magic' would be a fancy pattern.
This pattern {0,5:###.0} should work:
string.Format("{0,5:###.0}", 12.3456) //Output " 12.3"
string.Format("{0,5:###.0}", 10.011) //Output " 10.0"
string.Format("{0,5:###.0}", 123.123) //Output "123.1"
string.Format("{0,5:###.0}", 1.123) //Output " 1.1"
string.Format("{0,5:###.0}", 1234.123)//Output "1234.1"
Another one with string interpolation (C# 6+):
double x = 123.456;
$"{x,15:N4}"// left pad with spaces to 15 total, numeric with fixed 4 decimals
Expression returns: " 123.4560"
value.ToString("N1");
Change the number for more decimal places.
EDIT: Missed the padding bit
value.ToString("N1").PadLeft(1);
Many good answers, but this is what I use the most (c# 6+):
Debug.WriteLine($"{height,6:##0.00}");
//if height is 1.23 => " 1.23"
//if height is 0.23 => " 0.23"
//if height is 123.23 => "123.23"
All above solution will do rounding of decimal, just in case somebody is searching for solution without rounding
decimal dValue = Math.Truncate(1.199999 * 100) / 100;
dValue .ToString("0.00");//output 1.99
Note the "." could be a "," depending on Region settings, when using string.Format.
string.Format("{0,5:###.0}", 0.9) // Output " .9"
string.Format("{0,5:##0.0}", 0.9) // Output " 0.9"
I ended up using this:
string String_SetRPM = $"{Values_SetRPM,5:##0}";
// Prints for example " 0", " 3000", and "24000"
string String_Amps = $"{(Values_Amps * 0.1),5:##0.0}";
// Print for example " 2.3"
Thanks a lot!

Remove 0s from the end of a decimal value [duplicate]

This question already has answers here:
Remove trailing zeros
(23 answers)
Closed 9 years ago.
I have a decimal value that has a variable number of digits after the ., for example:
0.0030
0.0310
0.0001
1.1200
How can I write a dynamic function that removes 0 in the end of the decimal?
You can also modify the decimal itself so that any ToString() will give you what you want
(more details in my answer here) :
public static decimal Normalize(decimal value)
{
return value/1.000000000000000000000000000000000m;
}
string.Format("{0:0.#####}", 0.0030)
or
var money=1.3000m;
money.ToString("0.#####");
For future reference I recommend the .NET Format String Quick Reference by John Sheehan.
decimal value = 0.0030m;
value.ToString(“G29″);
Edit: The G formatter does work, the only problem is that it jumps to scientific notation if there are too many significant figures in the original decimal. Not so ideal.
See the "The General ("G") Format Specifier" documentation here: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#GFormatString
I'm on lunch, so I did a little test:
decimal d1 = 0.000100m;
decimal d2 = 0.001000000000000000000000m;
decimal d3 = 0.000000000000001000000000m;
Console.WriteLine(Environment.NewLine + "input decimal: 0.000100m");
Console.WriteLine("G " + d1.ToString("G"));
Console.WriteLine("G29 " + d1.ToString("G29"));
Console.WriteLine("0.####### " + d1.ToString("0.#######"));
Console.WriteLine(Environment.NewLine + "input decimal: 0.001000000000000000000000m");
Console.WriteLine("G " + d2.ToString("G"));
Console.WriteLine("G29 " + d2.ToString("G29"));
Console.WriteLine("0.####### " + d2.ToString("0.#######"));
Console.WriteLine(Environment.NewLine + "input decimal: 0.000000000000001000000000m");
Console.WriteLine("G " + d3.ToString("G"));
Console.WriteLine("G29 " + d3.ToString("G29"));
Console.WriteLine("0.####### " + d3.ToString("0.#######"));
Output:
input decimal: 0.000100m
G 0.000100
G29 0.0001
0.####### 0.0001
input decimal: 0.001000000000000000000000m
G 0.001000000000000000000000
G29 0.001
0.####### 0.001
input decimal: 0.000000000000001000000000m
G 0.000000000000001000000000
G29 1E-15
0.####### 0
Hmm, this is a display formatting issue (the zeros are added when you convert the decimal to a string).
You need to see where in code you are seeing the trailing zeros. Is it after a call to .ToString()? Try playing around with the different formatting strings:
.ToString("#");
.ToString("0.00");
.ToString("#.##");
And so on. The best way to do this is just to experiment with the different possible values.
decimal m = 0.030000m;
Console.Write(m.ToString("0.##########"));
Just make sure you have enough #s for the number of decimal places you want to display
I use the following. It ensures that any decimal (for which the max precision is 29 decimal places) will show all available digits of precision without trailing zeros, and without your code needing to have a long ugly string of hash marks.
if (value is Decimal)
value = ((Decimal)value).ToString("0.".PadRight(29, '#'), culture);
public static string GentlyRemoveEndZeros(string input)
{
// if (input == null) return null;
// if (input == "") return "";
if (input.Contains(".")) return input.TrimEnd('0').TrimEnd('.');
return input;
}

Categories

Resources