String Format wrong format for % [duplicate] - c#

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 = "\\%;

Related

Line up Characters

I have a combobox made up of two numbers; inches and millimetres. At the moment it is looking hideous. I am wondering if some of the gurus here have anyway of lining the character '|' or at least make it nicer?
A bit of background info, the number inches and millimetres are separate strings which I append together like so:
Size(in) + " (In) | " + Size(mm) + " (mm)"
Possibly the cleanest way would be to format every number to have 3 decimal places for at least inches. This still won't be perfect however since the letter font width won't be perfect, to fix that you'd need to use a monospaced font.
To format to 3dp you can use the following
String.Format("{0:f3}", Size(in)) + " (In) | " + Size(mm) + " (mm)"
Since you have some values that are 2 digits before the decimal you can always use PadLeft to align these, but again this doesn't always work well without a monospaced font..
String.Format("{0:f3}", Size(in)).PadLeft(5, ' ') // or (5, '0')
Use String.PadRight(i); and String.PadLeft(i); where i is a nr. of spaces to "fill":
Example:
// Just to simplify a little, create vars:
var inches = Size(in) + " (In) ";
var mm = " + Size(mm) + " (mm)";
var formatted = inches.PadRight(15) + "|" + mm.PadLeft(15);
Example of output using 15 for the padding value (obviously, you can adjust this as needed):
43 inches | 123 cm
445554 inches | 12345 cm

How to search for rows within 2 date intervals using Dataset.Tables.Select method?

I have a database table "Leave".
Its primary key is "LeaveNo".
The other fields in the database include "LeaveDate", "EmpID" , "EmpName" , etc
I want to use the dataset.tables["Leave"].Select() method to acquire only the leaves the employee has made in a single month.
The best way I figured was to use two intervals i.e mm/01/2012 and mm/31/2012
(I know some months have 30 days)
My current code is this and it does not work:
This was just a test code...
string moreThan = DateTime.Now.Month.ToString() + "01" + DateTime.Now.Year.ToString();
string lessThan = DateTime.Now.Month.ToString() + "31" + DateTime.Now.Year.ToString();
leavesthisMonth = LeaveDS.Tables["Leave"].Select("EmpID='" + txt_EmpID.Text + "' AND LeaveDate <= '" + "#" + lessThan + "#" + "'" + "AND LeaveDate >= '" + "#" + moreThan + "#" + "'");
Can someone help me with this ???
Working with DataSets and DataTables means that you are not bound (or anyway no more) to a database or specific SQL dialect.
The syntax used with the DataTable.Select() method is documented on MSDN.
For dates (obviously if the column type is REALLY DateTime) is used a syntax similar to MS Access (# delimited), so you can write:
var rows = dt.Select("LeaveDate > #2013-01-01#");
Is important to NOT use quotes (as in #Waqas code):
var rows = dt.Select("LeaveDate > '#2013-01-01#'"); // ERROR
because results in: System.FormatException: String was not recognized as a valid DateTime.
My advice is to use the yyyy-MM-dd format because is culture invariant by design.
A good way to build strings with a specific syntax is to use String.Format (or any variants) for clarity reasons, and let the DateTime type do all the specific date maths.
int month = 10;
var begin = new DateTime(DateTime.Today.Year,month,1); // first day of a month
var end = begin.AddMonths(1); // first day next month
var format = "LeaveDate >= #{0:yyyy-MM-dd}# AND LeaveDate < #{1:yyyy-MM-dd}#";
var condition = String.Format(format,begin,end);
rows = dt.Select(condition);
Notice your operator <= LeaveDate and >= LeaveDate
The operator it should be like >= LeaveDate and <= LeaveDate
The LeaveDate it should be like LeaveDate.ToString("dd MMM yyyy") or LeaveDate.ToString("dd/mm/yyyy")
leavesthisMonth = LeaveDS.Tables["Leave"].Select("EmpID='" + txt_EmpID.Text + "' AND (LeaveDate >= #" + lessThan + "# AND LeaveDate <= #" + moreThan + "#)");
You could make the whole thing a lot easier by using Date() in the SQL:
WHERE Month(LeaveDate)=Month(Date()) AND Year(LeaveDate)=Year(Date())
That removes all the date handling to MS Access and avoids a lot of problem.

signed numbers + or - [duplicate]

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.

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