Display Positive Infinity in console - c#

Simply speaking console displays positive infinity as ? instead of ∞. Example code:
var a = double.PositiveInfinity;
Console.WriteLine(a); //displays ? instead of ∞
I have tried using Invariant Culture, Console.OutputEncoding = System.Text.Encoding.UTF8, and Console.OutputEncoding = System.Text.Encoding.Unicode. Always displays ?.
P.S
Writing it to a file does work and it displays correctly, but it would be nice if it also displayed properly on console.

Related

Output numeric formatting is wrong

I'm writing a program in C# that turns the number (given by an user) to a decimal number with the $ mark. For example, if i give in 15 then the results should be $15.00 but the results now is 15.00 ?.
I have tried to put en-US behind it but it doesn't work
Console.Write("Give a number that you want to convert to $: ");
int number = int.Parse(Console.ReadLine());
Console.WriteLine("Money: {0}", number.ToString("C"));
Edit:
My teacher doesn't allow it to just put "$" in front of it.
This should work regardless of your machine's culture info:
Console.WriteLine("Money: {0}",
number.ToString("C", System.Globalization.CultureInfo.CreateSpecificCulture("en-US")));

Conditional Formatting Hides Text

I have an Excel worksheet which I'm adding conditional formatting to from an add-in written in C#.
The condition fires ok and I'm able to change the fill colour but the text always gets hidden.
If I remove the fill colour from the format, the text still gets hidden when the formatting is applied.
If I remove all the formatting and just apply the condition without any format changes, the text is still hidden.
When the format condition is no longer valid, the text appears as you would expect.
The cell value is definitely set correctly.
Why would this happen?
C# code as follows:
var disabledFormat = "IF(blah blah...),FALSE,TRUE)";
var formatCondition = (Excel.FormatCondition)cell.FormatConditions.Add(
Excel.XlFormatConditionType.xlExpression,
Type.Missing, disabledFormat);
formatCondition.Font.Color = ColorTranslator.FromHtml("#C0C0C0");
formatCondition.Interior.Color = ColorTranslator.FromHtml("#F0F0F0");
[Edit]
I have tried changing the colour to white, black, red etc. but it is still invisible when the conditional formatting applies.
[/Edit]
[Edit2]
Full disabledFormat string as requested:
(The code does not look exactly link this as it spans several classes, I've just tried to fill-in the blanks to be helpful :$)
const string FORMAT_DISABLED = "=IF(LEFT(MID('{2}'!{0},FIND(\"|\",'{2}'!{0},FIND(\"|\",'{2}'!{0})+1)+1,999),LEN(INDIRECT(\"'$lookup_grading'!\"&ADDRESS({1},1))))=INDIRECT(\"'$lookup_grading'!\"&ADDRESS({1},1)),FALSE,TRUE)";
var dropdownCell = "Q5";
var disabledFormat = string.Format(FORMAT_DISABLED, cellName, dropdownCell, controlSheetName);
Resolves to:
=IF(LEFT(MID('$controls_Distribution Grid'!W19,FIND("|",'$controls_Distribution Grid'!W19,FIND("|",'$controls_Distribution Grid'!W19)+1)+1,999),LEN(INDIRECT("'$lookup_grading'!"&ADDRESS(Q5,1))))=INDIRECT("'$lookup_grading'!"&ADDRESS(Q5,1)),FALSE,TRUE)
To try to clarify further, what this does is it looks up a value in a cell in another worksheet with the same address, grabs a value from a formatted string in that cell and compares it to the value indicated by the selected item in a dropdown. If there is a match TRUE is returned.
The same formula is also used to return 1 or 0 for the cell value so I know this works ok.
[/Edit2]
[Edit3]
I've narrowed the problem down to the NumberFormat, which is "a";;;.
When the conditional formatting does not trigger this correctly shows a (or a tick with Webdings applied).
But when the conditional formatting triggers the output from the NumberFormat does not appear.
I can't think why this would be intentional so I'm guessing this is a bug in Excel, but I'll do some Googling to check
[/Edit3]
This is the formula in the cell which returns a 1 or 0 (hope it's clear enough!):
=IF(
LEFT(
MID('$controls_Distribution Grid'!$V$19,
FIND("|",'$controls_Distribution Grid'!$V$19,
FIND("|",'$controls_Distribution Grid'!$V$19)+1
)+1,999),
LEN(INDIRECT("'$lookup_grading'!"&ADDRESS(Q5,1)))
)=INDIRECT("'$lookup_grading'!"&ADDRESS(Q5,1)),
1,0)
The definition of a number format is four fields separated by ;
<POSITIVE>;<NEGATIVE>;<ZERO>;<TEXT>
Your number format "a";;; means if the value is positive display a , if it's zero, negative or text display nothing.
Your formula returns TRUE or FALSE, which are treated as text, so when your condition fires, the format hides the cell value.
I suggest you change your formula to return 1 or 0 which will then display a or nothing
try using this
formatCondition.Font.ThemeColor = ColorTranslator.FromHtml("#909090");
formatCondition.Interior.ThemeColor = ColorTranslator.FromHtml("#F0F0F0");
formatCondition.Interior.PatternColorIndex = xlAutomatic;
I don't know if the PatternColorIndex is necessary or not, that is what I got from macro recording.
Edit:
this is the macro if that helps you:
With Selection.Font
.ThemeColor = xlThemeColorDark1
.TintAndShade = -0.499984740745262
End With
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark1
.TintAndShade = -0.149998474074526
.PatternTintAndShade = 0
End With
This sounds like it could be an error in the font file. Try a standard character A-Z to see it it disappears when formatted. If it doesn't disappear then you could have a corrupt font file. Might have to dump the wingdings font and re-install.

C# - How is ctrl+A input turned into a smiley?

While learning about Console.ReadLine() in depth, I found something very peculiar.
I wrote following code in Main method in a console application in C#
string str = Console.ReadLine();
Console.WriteLine(str);
Console.WriteLine(str.Trim());
Console.ReadLine();
When I ran the code, I gave input as ctrl+A and pressed enter. I see smileys (not able to post image, as I don't have permission to do it yet).
I want to understand, how is it showing the smiley? Shouldn't it show ^A or empty/blank (empty because when I tried debugging it, it showed string value a " ".)
If you look at that Encoding used by Console then you can see that it is used IBM437.
Now go to page : http://en.wikipedia.org/wiki/Code_page_437
You will find that 1 has Smiley.
When you press ctrl + A , it will traslated into 1.
So you get that smiley.
string str = Console.ReadLine();
Console.WriteLine((int)str[0]); // Integer value of character.
// Console.OutputEncoding ( to get further detail)
Console.ReadLine();
The smiley is just how the console displays U+0001 (start of heading) - and that's the character that apparently is read as input from the console when you type Ctrl-A... a bit like the way that if you type Ctrl-G you get U+0007 (bell).
This isn't really .NET behaviour, so much as the Windows console behaviour (both input and output) - I can reproduce exactly the same behaviour in Java, for instance.

C# Default Format For Comma-Delimited Numbers

I have a C# application that displays some large numbers in a textbox. I want it to use a comma as a thousands separator. I use the following code to do that:
txtNumberDisplay.Text = intNumber.ToString("N0");
The above was working fine until recently it was displaying numbers correctly in the form of:
123,456
Recently the thousands separator has somehow changed to a period "." and the numbers display like this:
123.456
My first thought was the culture had somehow gotten set incorrectly but I checked the default culture for the current thread at the point it displays this number and it is set correctly to "EN-US". Any idea why this would display a period instead of a comma?
Thanks,
use string.Format:
int value = 1234;
string.Format(#"{0:#\,##0}", value);
//Output will be 1,234
EDIT: added an \,
EDIT2: Just found out that this wont work on numbers with 6 digits (two commas would be needed), so here is a workarount, but there must be a better solution...
int value = 1234;
string s = "#";
for (int i = 0; i < value.ToString().Length / 3; i++) s += #"\,###";
string output = string.Format(#"{0:" + s + "}", value);
My first thought was the culture had somehow gotten set incorrectly but I checked the default culture for the current thread at the point it displays this number and it is set correctly to "EN-US". Any idea why this would display a period instead of a comma?
Either the culture is something different than "en-US" or you have customized the number format in the regional settings in the control panel.
When you execute intNumber.ToString("N0") without specifying a culture the culture used is Thread.CurrentThread.CurrentCulture. Perhaps you examined Thread.CurrentThread.CurrentUICulture which is based on the language version of Windows and not used for formatting?
If the current culture really is "en-US" you should go to Control Panel -> Clock, Language, and Region -> Change date, time, or number formats and make sure that the Digit grouping symbol is comma and not dot. The symbol shown in the control panel is the symbol used when you do not specify a CultureInfo when you format the number.
You have several options:
Force the culture when formatting, e.g. intNumber.ToString("N0", CultureInfo.InvariantCulture) to get commas as you desire.
Realize that the user should be able to control the formatting. This is what your code currently does.
This should work perfectly fine:
int.ToString("F", CultureInfo.InvariantCulture);
Windows 8.1 (and probably 8 as well) has incorrect culture regional settings stored.
Therefore, if you rely on ToString("formatstring", desired_culture) it won't work.
Since you write
[...] The above was working fine until recently it was displaying numbers
correctly [...]
I suppose in-between the working and not-working, you upgraded to Windows 8 or 8.1, which explains why it suddenly stopped working.
For example for culture German - Switzerland ("de-CH") it incorrectly sets the NumberDecimalSeparator to "," instead of "." (and the thousand-separator to " " instead of "'") and therefore copy-pasting to Excel won't work anymore (Excel seems to somehow use a non-system format).
You best hardcode your number format, because that's the only way to keep it working across windows-versions.
This is how I do it (you might want to change the separators and the currency-symbol):
private static System.Globalization.NumberFormatInfo SetupNumberFormatInfo()
{
//System.Globalization.NumberFormatInfo nfi = (System.Globalization.NumberFormatInfo)System.Globalization.CultureInfo.InvariantCulture.NumberFormat.Clone();
System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo();
nfi.NumberGroupSeparator = "'";
nfi.NumberDecimalSeparator = ".";
nfi.CurrencyGroupSeparator = "'";
nfi.CurrencyDecimalSeparator = ".";
nfi.CurrencySymbol = "CHF";
return nfi;
} // End Function SetupNumberFormatInfo
private static System.Globalization.NumberFormatInfo m_nfi = SetupNumberFormatInfo();
public static string ToNumberString(this double dblQuantity)
{
return ToNumberString(dblQuantity, "N0");
}
public static string ToNumberString(this double dblQuantity, string Format)
{
// http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo%28VS.71%29.aspx
//double dblQuantity = -123456789.123456789;
//string strFormattedInteger = dblQuantity.ToString("N0", m_nfi);
//strFormattedInteger = string.Format(m_nfi, "{0:N0}", dblQuantity);
return dblQuantity.ToString(Format, m_nfi);
}

Custom numeric format string based on number sign

I am trying to format a decimal (as a percentage without the % sign), displaying brackets () around negative numbers and displaying positive numbers as is.
var returnString = value.HasValue
? string.Format("{0:0.0;(0.0)}", value.Value * 100) :
DefaultEmptyString;
return returnString;
My main problem is that for a numbers such as -0.000491 which in this formatting scheme is a zero it should still show the brackets as it is a negative zero.
Nonetheless, it is being lost.
I could stop using the section separator and utilize an if statement instead but it seems like the section separator should do the trick.
Any ideas why the formatting is not done correctly ?
Any ideas why the formatting is not done correctly ?
Is is done correctly according to the documentation:
If the number to be formatted is negative, but becomes zero after rounding according to the format in the second section, the resulting zero is formatted according to the first section.
Since I don't see any options available that would override that default behavior, one option is to append the parentheses manually:
public string Format(decimal value)
{
string s = (value*100).ToString("0.0;0.0");
if(value < 0)
s = "(" + s + ")";
return s;
}
From the documentation: http://msdn.microsoft.com/en-US/library/0c899ak8%28v=vs.80%29.aspx
"If the number to be formatted is negative, but becomes zero after rounding according to the format in the second section, then the resulting zero is formatted according to the first section."
The formatting is correct, you will need the if statement.

Categories