c# How to print a double in a custom scientific notation - c#

I am trying to build a custom format specified for doubles for a two line element (tle) for space objects. From the wiki documentation TLEs
Where decimal points are assumed, they are leading decimal points. The last two symbols in Fields 10 and 11 of the first line give powers of 10 to apply to the preceding decimal. Thus, for example, Field 11 (-11606-4) translates to −0.11606E−4 (−0.11606×10−4).
This field is 8 characters long. First character is +/-/' ' followed by 5 numeric values (No zero padding) followed by a '-' and a single exponent value.
Does anyone know how to build this inline? ie $"{val,someFormat}" This would be preferred however I don't think it is possible so the alternative would be composing it of several pieces like
$"{val<0?"-":" "}{frac(val)}-{getExp(val)}".
Both frac() and getExp() need to be built, but my biggest problem is how to get the exponential value of the double. Is there any built in function that will return an int value of the exponent of a double? With that I think I can build everything else.
Again if there is an easier way I am all ears!
Thanks

Related

Is there a way to format a C# double exactly? [duplicate]

This question already has answers here:
Formatting doubles for output in C#
(10 answers)
Closed 8 years ago.
Is there a way to get a string showing the exact value of a double, with all the decimal places needed to represent its precise value in base 10?
For example (via Jon Skeet and Tony the Pony), when you type
double d = 0.3;
the actual value of d is exactly
0.299999999999999988897769753748434595763683319091796875
Every binary floating-point value (ignoring things like infinity and NaN) will resolve to a terminating decimal value. So with enough digits of precision in the output (55 in this case), you can always take whatever is in a double and show its exact value in decimal. And being able to show people the exact value would be really useful when there's a need to explain the oddities of floating-point arithmetic. But is there a way to do this in C#?
I've tried all of the standard numeric format strings, both with and without precision specified, and nothing gives the exact value. A few highlights:
d.ToString("n55") outputs 0.3 followed by 54 zeroes -- it does its usual "round to what you probably want to see" and then tacks more zeroes on the end. Same thing if I use a custom format string of 0.00000...
d.ToString("r") gives you a value with enough precision that if you parse it you'll get the same bit pattern you started with -- but in this case it just outputs 0.3. (This would be more useful if I was dealing with the result of a calculation, rather than a constant.)
d.ToString("e55") outputs 2.9999999999999999000000000000000000000000000000000000000e-001 -- some of the precision, but not all of it like I'm looking for.
Is there some format string I missed, or some other library function, or NuGet package or other library, that is able to convert a double to a string with full precision?
You could try using # placeholders if you want to suppress trailing zeroes, and avoid scientific notation. Though you'll need a lot of them for very small numbers, e.g.:
Console.WriteLine(double.Epsilon.ToString("0.########....###"));
I believe you can do this, based on what you want to accomplish with the display:
Consider this:
Double myDouble = 10/3;
myDouble.ToString("G17");
Your output will be:
3.3333333333333335
See this link for why: http://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx
By default, the return value only contains 15 digits of precision although a maximum of 17 digits is maintained internally. If the value of this instance has greater than 15 digits, ToString returns PositiveInfinitySymbol or NegativeInfinitySymbol instead of the expected number. If you require more precision, specify format with the "G17" format specification, which always returns 17 digits of precision, or "R", which returns 15 digits if the number can be represented with that precision or 17 digits if the number can only be represented with maximum precision.
You can also do:
myDouble.ToString("n16");
That will discard the 16th and 17th noise digits, and return the following:
3.3333333333333300
If you're looking to display the actual variable value as a number, you'll likely want to use "G17". If you're trying to display a numerical value being used in a calculation with high precision, you'll want to use "n16".

how to convert 2.0 to four precision floating point number in c#

I have the following code:
float f = 0.02;
The results are equivalent to:
f = 0.0200
How to do this in C#?
A floating point number has a value (for example 0.02).
When you print it, you can format it into any number of different representations, including "0.002", "0.00200" and "scientific notation". It's the same value with the same precision - it's just printed differently (perhaps with a different number of digits after the decimal).
I believe your question is about "formatting":
String s = String.Format("{0:0.0000}", 0.002);
Here is much more detail:
http://msdn.microsoft.com/en-us/library/s8s7t687.aspx
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
http://www.dotnetperls.com/string-format
Under the hood, the number is still the same whether the trailing zeros are shown. You can't change what the number is, but you can change how it displays by using a .ToString() overide.
Specifically the Zero custom specifier.

converting a string of binary into a string of decimal c#

problem is to convert a string of binary digits into its decimal representation. Easy eh?
well, it needs to be able to handle input of over 64 bits in length and convert it without using any external libraries or data types like big integer.
How can I do this?
so far i have a string called input which handles the binary
I then access each digit using input[0] etc to get a char representing that digit.
Now I manipulate it and multiply by the corresponding power of 2 that its index represents, and move through the array storing the total as i go.
I use a big integer to store the total as for large numbers the primative types dont work.
My first solution works perfectly, how can I do this without using anything to store the total, i.e only using strings to store answers.
Any Ideas?
Thanks
You will need an array of digits to hold the result. An array of int's would be easier but you can also use the final string. You can calculate it's length from the length of the inputstring, you may have to remove leading zero's in the end.
Calculate your result as before but do the adding (including the carrying) in the result array.
I think this is a (homework) assignment that wants you to implement a version of the "pen & paper" addition method.

Convert.ToSingle rounding

I made a query to SQL Server to get some data via a Stored Procedure, the returned value was this:
10219150
Then, in an assembly (I don't have the source code of that assembly, I reflected the file to view the code) someone had written this:
Amount = Convert.ToSingle(10219150); //the value from the stored procedure
So, when I invoke that method which does the final conversion, it returns this value:
1.021315E+7
How is that possible? Why does the Convert.ToSingle add extra decimal positions? I don't understand.
Is there a way that i can reverse that conversion on my code when I invoke that method of the assembly? I can't rewrite that assembly file as it's too big, and, as I mentioned earlier, I don't have the source code to fix the conversion.
From this: 1.021315E+7 To this: 10219150 again (restore the correct value without that conversion)
Hope I made myself clear.
Thanks in advance.
The conversion to single isn't adding extra precision.
10219150 is 1.021315E+7 (which is just another way of writing 1.021315 * 107).
The method you are using to print out the value is just using scientific notation to display the number.
If you are printing the number then you need to set the formatting options.
float amount = Convert.ToSingle("10219150");
string toPrint = string.Format("{0:N}", amount);
Will print the number as:
"10,219,150.00"
To get no decimal places use "{0:N0}" as the format string.
You have two issues. One is easily solved, and the other may be more difficult or impossible.
As ChrisF stated, 1.021315E+7 is simply another way of writing 10219150. (The E+7 part in Scientific Notation means to shift the decimal point 7 places to the right.) When you format your single precision value, you can use
fvalue.ToString("f0");
to display as an integer, rather than in Scientific Notation.
The bigger problem, unfortunately, is that a single precision float can only hold 7 significant digits, and in your example you are storing 8. Therefore, the last digit may be rounded. (Since it happens to be 0 in your case, the rounding might not have been noticed.)
If that loss of precision is critical, you would likely need to fetch the value from the database as a long, or as a double-precision value (depending on the type of data returned.) Each of these types can hold more significant digits.
When the value is converted to Single, it's rounded as it contains more significant digits that can fit in a Single. If you convert 10213153 to Single you also end up with 1.021315E+7 i.e. 10213150.
As the code uses a Single to store the amount, there is nothing that you can do to make it handle the current value correctly. The amount simply can not be represented correctly as a Single.
You either have to use lower values, or change the code.

ODP ADO.NET driver returns decimal with extra zero in string representation

Today's problem is as follows: we have a table in an Oracle database. The table contains a field that is of the type Number(18, 3).
On the surface, both saving and loading data from said field work perfectly. However, further inspection reveals, that numbers that have three decimal digits in them, e.g. 500.001, are read from the database in such a way that the string representation of the decimal has a fourth, zero digit (e.g. 500.0010). This seems to happen whenever the third decimal digit is nonzero.
For math purposes, this is not a problem. However, we have validators that verify the number of decimal digits in a decimal number by converting it to a string and then counting the number of decimal digits. Since this particular piece of data is defined to have at most three decimal digits, the extra zero causes a validation error.
Since I can't change the validators, I'm left wondering if there is a clean way to get the decimal without the extra zero, apart from converting the number to a string, trimming the trailing zeroes and then re-parsing it? Or should I be doing something different altogether?
Try this:
decimal trimmed = ((decimal)((int)(number * 1000))) / 1000
Casting to int gets rid of the fractional part. You don't need all the parentheses but I think it's easier to see what's going on if the order of operations is explictily indicated.
I ran into the same issue but I used: number.ToString("F3")

Categories

Resources