Convert long Double to Int? - c#

Trying to convert the following value:
9.40551020088303E+21
to
9405510200883031584406
I am a but lost on how to do this? Math.Round, (int)Value.
Edit: Ok i may be wrong here, but i am trying to convert this to 9405510200883031584406 in anyway possible, it can be a string, or different type.
The final result is a tracking number and what i am starting with is what the shipping company provides me with.

the closest thing I can think of is using BigInteger
double d = 9.40551020088303E+21;
BigInteger bi = new BigInteger(d);
Console.WriteLine(bi.ToString());
Output would be:
9405510200883030261760

What you're describing isn't possible. An int (Int32) data type has a maximum value of 2147483647.
the long (Int64) data type, can only go up to 9,223,372,036,854,775,807
an unsigned long (UInt64) can go to 18,446,744,073,709,551,615
The number is simply too large for any of those data types.
9,405,510,200,883,031,584,406 (Your value)
9,223,372,036,854,775,807 (Int64.MaxValue)
18,446,744,073,709,551,615 (UInt64.MaxValue)

If you just want to convert this to a string as in your question it can be a string, or different type. Than this should suffice.
decimal value = 9405510200883031584406m;
string str = value.ToString("F0");
However, this assumes you know the actual full number. You can't convert 9.40551020088303E+21 to a more precise value, if you don't know the trailing digits.
You can see how to format in Standard Numeric Format Strings
The fixed-point ("F) format specifier converts a number to a string of
the form "-ddd.ddd…" where each "d" indicates a digit (0-9). The
string starts with a minus sign if the number is negative. The
precision specifier indicates the desired number of decimal places. If
the precision specifier is omitted, the current
NumberFormatInfo.NumberDecimalDigits property supplies the numeric
precision.

Related

how to add zeros for integer variable

I'm very new to c# programming. I want to know how to add leading zeros for a integer type in c#.
ex:
int value = 23;
I want to use it like this ;
0023
Thanks in advance
You can't. There's no such contextual information in an int. An integer is just an integer.
If you're talking about formatting, you could use something like:
string formatted = value.ToString("0000");
... that will ensure there are at least 4 digits. (A format string of "D4" will have the same effect.) But you need to be very clear in your mind that this is only relevant in the string representation... it's not part of the integer value represented by value. Similarly, value has no notion of whether it's in decimal or hex - again, that's a property of how you format it.
(It's really important to understand this in reasonably simple cases like this, as it tends to make a lot more difference for things like date/time values, which again don't store any formatting information, and people often get confused.)
Note that there's one type which may surprise you: decimal. While it doesn't consider leading zeroes, it does have a notion of trailing zeroes (implicitly in the way it's stored), so 1.0m and 1.00m are distinguishable values.
Basically you want to add padding zeros.
string format specifier has a very simple method to this.
string valueAfterpadding;
int value = 23;
valueAfterpadding = value.ToString("D4");
Console.WriteLine(valueAfterpadding );
this solve your problem. just google it.
Integer wont accept leading zeros, it will only hold the real value of the integer.
The best we to have leading zeros is to convert it to string.
If you need a 4 digit value always, use the .ToString formatting to add leading 0's.
int value = 23;
var result = value.ToString("0000");
or if you want to have a leading 00 to any number, better append 00 to the string equivalent of the integer.
int value = 23;
var result = "00" + value.ToString();
This is not a programming issue. Numbers have no leading zeroes.
There are two things here that you can do:
If it is a number, then format it on the way out.
If it is something like a code (article number etc.) - those are NOT NUMBERS.
The second point is important. Things like social security numbers, part numbers etc. are strings - with only numeric characters allowed. You never add or subtract them and you must be prepared for format changes. They are not integers or any other number form to start with.

How to correctly convert a decimal value to exponential and exponential to decimal?

I am trying decimal to exponential conversion
decimal Additive = 0.083333001;
string expoAdditive = string.Format("{0:#.0#E-00}",Additive);
// I got this value :8.33E-02
// exponential to decimal conversion
decimal num = decimal.Parse(expoAdditive, System.Globalization.NumberStyles.Any);
// I got this value num = 0.0833 which is wrong. I need my correct value (0.083333001)
You need to provide enough precision in the formatting string. Otherwise, when you parse the string to try to recover the value, it's just not there.
It's not clear from your question why you're using the format string you are. But to get the necessary 7 digits of precision to accommodate the fractional part of 8.3333001, you either need to specify 7 explicit places in your format (e.g. "{0:#.0######E-00}"), or just use the simplified formatting string of "{0:E7}".
Of course, if you have other numbers you also need to handle which have more significant digits, then you'll have to adjust the precision accordingly. Seven digits may or may not be enough for you in every case.

Double to String Format text format

i have the follwing lines of code
double formId=2013519115027601;
txtEditFormID.Text = formid.ToString();
it gives me output
2.0135191150276E+15
if i write
txtEditFormID.Text = formId.ToString("0.0", CultureInfo.InvariantCulture);
it gives me
2013519115027600.0
but i want the label text
2013519115027601
how to do it?
I don't have enough information about the usage of your formId variable.
As it is shown above it seems an error to use a double datatype when there is no decimals to work on. So redefining your variable as a long datatype will be easy and the conversion will be the same.
long formId=2013519115027601;
txtEditFormID.Text = formid.ToString();
Not to mention the added benefit to your code to work with whole numbers instead of floating point numbers.
However, if you want to maintain the current datatype then
txtEditFormID.Text = formId.ToString("R");
The Round Trip Format Specifier
When a Single or Double value is formatted using this specifier, it is
first tested using the general format, with 15 digits of precision for
a Double and 7 digits of precision for a Single. If the value is
successfully parsed back to the same numeric value, it is formatted
using the general format specifier. If the value is not successfully
parsed back to the same numeric value, it is formatted using 17 digits
of precision for a Double and 9 digits of precision for a Single.
Your first option is to use data type as long or decimal . Something else you can do if you want to keep using double is this :
double formId = 2013519115027601;
string text = formId.ToString();
txtEditFormID.Text = text.Replace(".",string.Empty);
this will remove all the '.' chars
There are times where I want calculations handled in double but I want the result displayed as as an int or even rounded amount, so the question isn't so strange (assuming that the given sample is simplified in order to ask the question).
I was going to post sample code for rounding, but it makes more sense to just use the built-in method Math.Round(). You can cast to a long, as mentioned above, but you won't have rounding, if desired (which it usually is, IMHO).
txtEditFormId.Text = ((long)formId).ToString();

C# Convert.ToDouble() loses decimal points when converting string to double

Let's say we have the following simple code
string number = "93389.429999999993";
double numberAsDouble = Convert.ToDouble(number);
Console.WriteLine(numberAsDouble);
after that conversion numberAsDouble variable has the value 93389.43. What can i do to make this variable keep the full number as is without rounding it? I have found that Convert.ToDecimal does not behave the same way but i need to have the value as double.
-------------------small update---------------------
putting a breakpoint in line 2 of the above code shows that the numberAsDouble variable has the rounded value 93389.43 before displayed in the console.
93389.429999999993 cannot be represented exactly as a 64-bit floating point number. A double can only hold 15 or 16 digits, while you have 17 digits. If you need that level of precision use a decimal instead.
(I know you say you need it as a double, but if you could explain why, there may be alternate solutions)
This is expected behavior.
A double can't represent every number exactly. This has nothing to do with the string conversion.
You can check it yourself:
Console.WriteLine(93389.429999999993);
This will print 93389.43.
The following also shows this:
Console.WriteLine(93389.429999999993 == 93389.43);
This prints True.
Keep in mind that there are two conversions going on here. First you're converting the string to a double, and then you're converting that double back into a string to display it.
You also need to consider that a double doesn't have infinite precision; depending on the string, some data may be lost due to the fact that a double doesn't have the capacity to store it.
When converting to a double it's not going to "round" any more than it has to. It will create the double that is closest to the number provided, given the capabilities of a double. When converting that double to a string it's much more likely that some information isn't kept.
See the following (in particular the first part of Michael Borgwardt's answer):
decimal vs double! - Which one should I use and when?
A double will not always keep the precision depending on the number you are trying to convert
If you need to be precise you will need to use decimal
This is a limit on the precision that a double can store. You can see this yourself by trying to convert 3389.429999999993 instead.
The double type has a finite precision of 64 bits, so a rounding error occurs when the real number is stored in the numberAsDouble variable.
A solution that would work for your example is to use the decimal type instead, which has 128 bit precision. However, the same problem arises with a smaller difference.
For arbitrary large numbers, the System.Numerics.BigInteger object from the .NET Framework 4.0 supports arbitrary precision for integers. However you will need a 3rd party library to use arbitrary large real numbers.
You could truncate the decimal places to the amount of digits you need, not exceeding double precision.
For instance, this will truncate to 5 decimal places, getting 93389.42999. Just replace 100000 for the needed value
string number = "93389.429999999993";
decimal numberAsDecimal = Convert.ToDecimal(number);
var numberAsDouble = ((double)((long)(numberAsDecimal * 100000.0m))) / 100000.0;

Double precision when number converted from string

I’m getting numbers from a database. Some are stored as double in the database and some are stored as string.
What I want to do is count the decimal number of caracters so : 345.34938 would give me a result of 5.
As I said, some of my double come from the database as double and some as string. I’m wondering if there could be any kind of problem when casting the string numbers to double, hence giving me wrong result when trying to count the decimals.
I think I should be ok but I’m afraid that in some situations I’ll end up receiving wrong double numbers when they’re casted from the string (thinking about having 1.9999999 instead of 2.0, things like that)...
Is there any kind of risk that casting my number from string to double would give me strange result when stored as double in my application ? Am I being to frisky around that ?
Consider converting the string representations to System.Decimal with the decimal.Parse method. Because for a decimal there's a much better correspondence between the value of the number and its string representation. Also, it can handle more digits.
A System.Decimal will preserve trailing zeros present in the string (like "2.7500"), which a System.Double will not.
But if your strings never have more than 15 digits in total (including digits before the decimal point .), your approach with double will probably work. But the exact number represented almost always differs from "what you see" with a double, so the number of decimal figures is to be understood as what double.ToString() shows...
Maybe it's easier to just use the string directly, like
int numberOfDecimals = myString.Length - (myString.IndexOf('.') + 1);

Categories

Resources