How to get the best number format string? - c#

I read a lot of articles about number format string, ex: http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
I really not understand how to write the best format string. To get a excepted result, I can write some ways. Example: print number 1234567890 as a text "1,234,567,890". These ways give the same result:
1234567890.ToString("#,#")
1234567890.ToString("#,##")
"#,##" is the popular one on internet but why? Please give me some information how to write a good format string. Thanks.

As far as I can see, there is no difference between "#,#" and "#,##": both mean 'format a number with group separators and without the fractional part'. Refer to SSCLI source for general number formatting for the gory details.

In your case it does not matter, because you are using int. This format #,## and #,# are for doubles and means that print only two digits after decimal point

Related

Which data structure(or type) would be useful for defining the digit amount of a number?

Hi there fellow programmers,
I know that should be easy but I need to define the digit amount of a number for trying all the combinations in a project. The digit number shouldn't be affected by users actions because the change of the digit amount causes "Index out of range" error. (Yes, I am using arrays for this)
Let's say, I have to use four digit number.
int Nmr=1000;
Nmr--;
Console.Write(Nmr);// The output will be 999 but I need 0999
Using string type and if statements could lead to an alternative solution...
int Nmr=1000;
Nmr--;
string number=Nmr.ToString();
if (Nmr<1000) number="0"+number;
if (Nmr<100) number="00"+number;
if (Nmr<10) number="000"+number;
Console.Write(Nmr); //That gives me 0999
But then, it gives me complexity and unneccessary time loss which I wouldn't want to encounter. I am not even talking about the greater values.
So, what would you suggest?
Edit: Both ToString("0000") and PadLeft methods are useful.
Thank you Mateus Coutinho Martino and Blorgbeard. =)
You can specify a format when calling ToString - e.g.
string number = Nmr.ToString("0000");
See the docs: Int32.ToString(string) and Custom Numeric Format Strings.
Well, do with PadLeft method of String class ...
int Nmr=1000;
Nmr--;
Console.Write(Nmr.ToString().PadLeft(4,'0')); //That gives you ever four digits.
Or if you prefer better explained ...
int Nmr=1000;
Nmr--;
String number = Nmr.ToString();
Console.Write(number.PadLeft(4,'0')); // four digits again;
The "0" custom format specifier serves as a zero-placeholder symbol.
Here's a little idea for you:
double numberS;
numberS = 123;
Console.WriteLine(numberS.ToString("00000"));
Console.WriteLine(String.Format("{0:00000}", value));
// Displays 00123
You can look at https://msdn.microsoft.com/en-us/library/0c899ak8.aspx for more.

Convert text data into percentage in C#

I am getting data into a text field and I need to display it as a percentage. Is there a function to perform this?
Ex: in my column I have "0.5", "0.1","0.2","0.25" etc., which needs to be displayed as
50%,10%,20%,25% etc., What is the best way to do it?
You should do this in two phases:
Parse the text as a number so you've got the value as your "real" type. (As a general rule, parse from text as early as you can, and format to a string as late as you can... operations between the two will be a lot simpler using the natural type.)
Format the number as a percentage using the standard numeric format string for percentage
So:
decimal percentage = decimal.Parse(input);
string output = percentage.ToString("p0");
Notes:
You should consider both input and output culture; are you always expecting to use "." as the decimal separator, for example?
Use decimal rather than double to exactly represent the value in the text (for example, the text could have "0.1" but double can't hold a value of exactly 0.1)
You can add things like desired precision to the formatting; see the linked docs for details; the example gives just an integer percentage, for example
Easiest would be to parse it (must be a double) then convert it back to a string, formatting it as a percentage.
var percentageString = double.Parse(doubleString).ToString("p1");
Now, some of you hoity-toity types may say that decimal is the correct type to use in this case.
Well, yes, if you need an additional 12-13 digits of precision.
However, most of us real folk (and I'm all about keeping it real) are fine with double's 15-16 digits of precision.
The real choice is whether or not your code is using doubles or decimals in the first place. If you are using doubles in your code, just stick with doubles. If decimals, stick to decimals. What you definitely do want to avoid is having to convert between the two any more than is absolutely necessary, as there be dragons. And unexpected runtime bugs that can corrupt your data. But mostly dragons.

How does Int32.Parse() exactly parse the String?

I am a novice C# learner. I know the basic concepts of this language. While revising the concepts, I stumbled upon one problem - How does Int32.Parse() exactly work?
Now I know what it does and the output and the overloads. What I need is the exact way in which this parsing is accomplished.
I searched on the MSDN site. It gives a very generalized definition of this method (Converts the string representation of a number to its 32-bit signed integer equivalent.) So my question is - How does it convert the string into a 32-bit signed integer?
On reading more, I found out 2 things -
The string parameter is interpreted using the "NumberStyles" enumeration
The string parameter is formatted and parsed using the "NumberFormatInfo" class
I need the theory behind this concept. Also, I did not understand the term - "culture-specific information" from the definition of the NumberFormatInfo class.
Here is the relevant code, which you can view under the terms of the MS-RSL.
"Culture-specific information" refers to the ways numbers can be written in different cultures. For example, in the US, you might write 1 million as:
1,000,000
But other cultures use the comma as a decimal separator, so you might see
1'000'000
or:
1 000 000
or, of course (in any culture):
1000000

Preventing double.Parse from removing trailing zeros after decimal place?

When using double.Parse, it seems to like to string away any trailing (insignificant) zeros from the string that I'm converting. I would like double.Parse to keep to places after the decimal. For example, here is some code:
tobereturned.MouseSensitivty = double.Parse(String.Format("{0:#.##}", tempstring[1]));
Debug.WriteLine("Converted " + String.Format("{0:#.##}", tempstring[1]) + " to " + tobereturned.MouseSensitivty);
The Debugger then writes
Converted 4.00 to 4
So it seems like double.Parse is doing something fishy here.
P.S. MouseSensitivity is also of the type double, so I can't do any string operations on it.
Your question is meaningless. Doubles don't have "places after the decimal" in the first place. They don't store anything that looks remotely like a "decimal representation of a number" internally. In fact, they don't store anything internally that even looks like recognizable text.
It reports 4 because 4.00 is exactly equal to 4. It is displaying the number "exactly four with no fractional part" as text according to its default rules for converting numbers to text.
Please read this. Yes, it is long, and difficult, but it is simply not possible to use floating-point numeric types properly without a real understanding of this material - and it doesn't matter what language you're using, either.
The double data type is simply a number; it doesn't keep track of the string that was parsed to create the value. Its string representation only comes into play when .ToString() is called.
If you know you always want two places after the decimal you can right-fill with zeros.
it is not the job of the double type to keep track of your desired display format.
Double does not store redundant zeros. In your view or presentation layer, you might want to format it to show you want it to appear, e.g., String.Format("{0:#.##}", doubleVariable)

In C#, how can I display only a certain number of digits?

In my application, I have a TextBlock that I display a Double number in after the user presses a button. This number can be a very small decimal or a very large number needing exponential notation (i.e. 3.43e12). The problem is, the program prints so many digits that it overflows my TextBlock and the user can't see all the valid information.
So how can I restrict the Double to print so to not overflow the TextBlock?
The code I am using to set the text is:
theTextBox.Text = (split * input).ToString();
EDIT: Someone asked for specific examples, so I thought I would clarify something. I basically want the string to never be longer than, say, 10 characters. That way it will fit in the TextBlock. I guess the trick is, when should those 10 characters be decimal places, whole numbers, or scientific notation that is the trick...
Use Double.ToString(String), giving an appropriate format specifier, as described at http://msdn.microsoft.com/en-us/library/kfsatb94.aspx.
Have a looksee here
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
You can put your format string in as a param to the ToString method

Categories

Resources