Converting string to int without losing the zero in the beginning - c#

I tried int.parse, and convert class to convert a string to int.
While I'm converting. I'm losing the 0 in the beginning which i don't want.
Ex : 09999 becomes 9999 - I don't want this.
I want to keep it as it is.
How can i do that?

myNumber.ToString("D5");
//D represents 'Decimal', and 5 is the specified amount of digits you want the number to be always. This will pad your value with zeroes until it reaches 5 digits.

You cannot. An int is meant to represent a mathematical integer. The numbers 09999 and 9999 are exactly the same number, mathematically.
Perhaps there is a different problem here. Why do you need to do this? Maybe there's a better way to do what you want to do.

If you want to do something like always print your number with 5 places, it goes like
myNumber.ToString().PadLeft(5, '0');

No, int.Parse("09999") actually returns 0x0000270F. Exactly 32 bits (because that's how big int is), 18 of which are leading zeros (to be precise, one is a sign bit, you could argue there are only 17 leading zeros).
It's only when you convert it back to a string that you get "9999", presence or absence of the leading zero in said string is controlled by the conversion back to string.

you cannot. you will have to maintain the value as a string if you want it to remain that way.

Int values cannot have leading zeros

If you are just converting to int to test the value, keep the original data around and use the string value of it when you want the leading zeor. If you require the integer to have zero padding after mathematically working with it you will have to format it with sprintf or the like whenever you output it.

you cant, but if you need to cast it to int and keep the zeros you can create a copy of it and then cast it to int, then you will have two versions of it one as int and one as string.

// For our requirement that new ID's should be of same length as old ID's.
string strID = "002017";
int number = int.Parse(strID);
string newID = (++number).ToString("D" + strID.Length);

Although this is a old thread, but this can also help:
// convert to big integer
var bigIntBits = BigInteger.Parse(intNumber);
int indexOfOne = intNumber.IndexOf('1');
string backToString = new string('0', indexOfOne) + bigIntBits.ToString();

I had same problem;
Solved it with an if else
Couldn't find another solution for it

Related

C# formatting a number with thousand separators but keeping the decimal places count as is

I want to add a thousands separator to a double number but want to keep the decimal places as is i.e. dont want any rounding.
#,# is solving my problem of adding the thousand separator but how do I preserve the decimal places ? #,# strips off the part after ..
I cannot use any culture or something like that & the developer whose function I am calling has only given me a way of changing the format by passing as parameter strFormat.
I did check other posts & even the docs but somehow not able to figure this out.
string strFormat = "#,#";
string str = double.parse("912123456.1123465789").ToString(strFormat);
//Expected here 912,123,456.1123465789
//Actual Output 912,123,456
//912123456.123 should give 912,123,456.123
//912123456.1 should give 912,123,456.1
//912123456.1123465789 should give 912,123,456.1123465789
//912123456 should give 912,123,456
Well, after looking at the documentation on Microsoft, it would appear that there is no particular way to allow a floating point position in a number - all characters in a format string are character placeholders.
I would recommend that you either use a very nasty predetermined number of #s to set the width of the decimal position, or the slightly less (or possibly more, depending on your outlook) nasty option of reading all numbers into an array, determining the longest decimal position, then building a format of #s using the result.
At the end of the day, this is a single format string that you can put into place, test and ensure it works, then come back later and fix if you find a better alternative.
Also, this is one of those things where you could put the string into a configuration setting and change as and when you need to - far more flexible.
To be honest, this is a very slight thing to be worried about in the grand scheme of performance and writing a program.
Technically, Udi Y gets my vote!
If you know the max number of decimal places, e.g. 10, then use:
string strFormat = "#,#0.##########";
Update:
This max number is known.
According to Microsoft documentation a Double value has up to 15 decimal digits of precision (including both before and after the decimal point). More than 15 digits will be rounded.
So if you must invoke that method of 'double.parse' and can only send the format, this is the best you can do:
string strFormat = "#,#0.###############";
You can calculate the formatting dynamically for each number:
public static void Main()
{
var number = 1234.12312323123;
var format = GetNumberFormat(number);
Console.WriteLine(number.ToString(format));
}
public static string GetNumberFormat(double number)
{
var numberAsString = number.ToString();
var decimalPartSize = numberAsString.Substring(numberAsString.LastIndexOf('.') + 1).Length;
return $"N{decimalPartSize}";
}
So
number = 1234.12312323123
will give you 1,234.12312323123. Works for negative numbers as well. Also, as we work with strings, there won't be any rounding errors or precision artifacts.

Remove leading zeros from exponent when converting ToString

Let's say I have a double n = 0.00000123456
In one case I may want to show 1 decimal place
n.ToString("E1") => "1.2E-006"
In another case I may want to show 4 decimal places
n.ToString("E4") => "1.2346E-006"
But I don't want the leading zeros on the exponents, these numbers are for an axis where there is limited space.
I would like to see "1.2E-6" and "1.2346E-6" : nice - no leading zeros!
I read how can I remove zeros from exponent notation and I see I can use n.ToString("0.0E+0") and n.ToString("0.0000E+0") respectively.
That's great, but, given that I have an integer variable requiredDecimalPlaces telling me the number of decimal places I require at any time, would I have to create this format string with a loop, adding zeros each time?! That seems hacky. If this is the way to do it could somebody let me know? But like I said, converting my variable requiredDecimalPlaces (value 4 let's say) to a string "0.0000" and then appending "E+0" to the end in order to create "0.0000E+0" seems over-complicated.
There isn't a standard numeric format that will do that so you'll have to create a custom one. And the easiest way to create that format would be the following.
number.ToString("0." + new string('0', decimalPlaces) + "E+0");

How to remove decimal part from a number in C#

I have number of type double.
double a = 12.00
I have to make it as 12 by removing .00
Please help me
Well 12 and 12.00 have exactly the same representation as double values. Are you trying to end up with a double or something else? (For example, you could cast to int, if you were convinced the value would be in the right range, and if the truncation effect is what you want.)
You might want to look at these methods too:
Math.Floor
Math.Ceiling
Math.Round (with variations for how to handle midpoints)
Math.Truncate
If you just need the integer part of the double then use explicit cast to int.
int number = (int) a;
You may use Convert.ToInt32 Method (Double), but this will round the number to the nearest integer.
value, rounded to the nearest 32-bit signed integer. If value is
halfway between two whole numbers, the even number is returned; that
is, 4.5 is converted to 4, and 5.5 is converted to 6.
Use Decimal.Truncate
It removes the fractional part from the decimal.
int i = (int)Decimal.Truncate(12.66m)
Use Math.Round
int d = (int) Math.Round(a, 0);
Reading all the comments by you, I think you are just trying to display it in a certain format rather than changing the value / casting it to int.
I think the easiest way to display 12.00 as "12" would be using string format specifiers.
double val = 12.00;
string displayed_value = val.ToString("N0"); // Output will be "12"
The best part about this solution is, that it will change 1200.00 to "1,200" (add a comma to it) which is very useful to display amount/money/price of something.
More information can be found here:
https://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx
here is a trick
a = double.Parse(a.ToString().Split(',')[0])
Because the numbers after point is only zero, the best solution is to use the Math.Round(MyNumber)
//I am doing a basic Calculation here and this works for me.
// it takes values from textboxes and performs the following as far as I understand it. as I have only been coding now for a few months.
double VC2 = Convert.ToDouble(txt_VC_M16_Tap.Text); // converts to double.
double total2 = (VC2 * 1000) / (3.14157 * 14.5); // performs the calculation.
total2 = Math.Round(total2); //Round the result to a whole number(integer)
txt_RPM2.Text = Convert.ToString(total2); // converts result to string and puts it in the textbox as required.
// Hope this helps people that are looking for simple answers.

Convert.ToInt32 does not take the a zero ( 0 ) as a starting integer

I have a question or actually two regarding the
Convert.ToInt32 function or Int32.Parse.
It seems when I use Int32.Parse("06487965") or the other function it just seems to lose the 0.
So the output will be "6487965".
My questions:
Why is that exactly ?
How can I solve this without getting into crazy hacks ?
Leading-zeroes are purely a formatting idiom. An actual number has no leading zeroes as they make no sense and are superfluous.
You don't really have anything to solve, BUT, if you want to display the number at a later point with a leading zero, then you can use string formatting to achieve this.
int myNum = 6487965;
string formatted = string.Format("{0:00000000}", myNum);
Leading zeroes do not make sense mathematically
You can't have leading zeroes in an integer, if you must have leading zeroes best way is to keep your variable as string.
Because in that form, the leading 0, or 0s is/are nonsensical and redundant.
It can become useful in terms of formatting, for visual representation when you know how it should be formatted, but otherwise it is a non-issue.
Leading zeroes are meaningless when converting to a numeric type like Int32 - it only cares about the actual numeric value represented by the string you're converting from, which is the same regardless of the number of zeroes stuck on the front.
If later on in your program you want to convert your Int32 back to a string or output it to your user then at that point you need to do some formatting to get the number of leading zeroes you want. The MSDN article "How to: Pad a Number with Leading Zeros" would be a good place to start with that.
Leading 0's aren't represented when you ToString an int by default. You want to pass a format like "00000000".
int value = Int32.Parse("06487965");
string stringAgain = value.ToString("000000000");
integer 06487965 equals to integer 6487965
because, nobody uses pading, here is it:
int intValue = Int32.Parse("06487965");
string stringAgain = intValue.ToString().PadLeft(9, '0');

How to best approach rounding up decimals in C#

I've decimal value 18.8. Values that are stored in this variable can be of any kind. For example it can be 1.0000000 or 1.00004000 or 5.00000008.
I would like to write a method so that I can pass decimal to it and get rounded up string. This wouldn't be a problem if I would know decimal places I would like to get. But what I would like to get is:
When it's 1.0000000 it should return 1.
If it's 1.00004000 it should return 1.00004.
When it's 5.00000008 it should return 5.00000008.
So basically it should find all 0 that are behind last digit different then 0 and cut it off.
How should I approach it? What's the best method? I'm getting this value from SQL and put it in decimal variable but then i would like to display it and having 5.0000000 when it could be displayed as 5 is a bit overkill for me.
Hope I could get some nice suggestions.
AFAIK, ToString( "0.##" ) will do, just increase number of # so that your value won't round up. E.g.:
decimal d = 1.999m;
string dStr = d.ToString("0.###");
This will generate "1,999" string (delimiter depends upon used culture).
As a result, you can use common very long formatting string: "0.############################" - to format all your values.
So trim the zeroes from the end.
decimal d = 1.999m;
string dStr = d.ToString().TrimEnd('0').TrimEnd('.');
You can also use string.Format and here's the documentation of the different possible formats but I like Johan Sheehans cheat sheet more as a quick reference.
decimal number=4711.00004711m;
4711.00004711
string.Format("{0:0.#############}",number);
"4711,00004711"
number=42;
42
string.Format("{0:0.#############}",number);
"42"
Take a look at Jon Skeets article: http://www.yoda.arachsys.com/csharp/floatingpoint.html

Categories