parsing float into string - c#

I have a number like so: 4.47778E+11
Can anyone give me a way of converting that into its number representation easily in c#?
Thanks

string s = "4.47778e+11";
double d = double.Parse(s);
or
string s = "4.47778e+11";
if (double.TryParse(s,out d))
{
// number was parsed correctly
}
or for internationalization
double.Parse("4.47778e+11", System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture);

Try this MSDN thread. It's called scientific notation by the way, and a quick google normally solves simple issues.
That's assuming you mean parsing from a string to a float, your question & title are conflicting

Use
float num = Convert.ToFloat(Convert.ToDouble(s));
But you still lose precision, floats are only precise to 7 digits, so you're better off using just the Convert.ToDouble() (precise to 15 or so digits), so you won't lose any digits in your example.

Use Convert:
double value = Convert.ToDouble("4.47778E+11");

Related

"Double" data type formatting [duplicate]

I want to convert this string: 0.55000000000000004 to this double: 0.55.
How to do that?
you can use this code to reduce precision part:
double m = Math.Round(0.55000000000000004,2);
Result would be : 0.55
Is a string or a double?
If it is a string:
double d = double.Parse(s,CultureInfo.InvariantCulture);
string s=string.Format("{0:0.00}",d);
if it is already a double just format using the second line.
There is no double 0.55 - the number cannot be accurately represented as a binary fraction. Which is probably the reason why you got that long string in the first place. You should probably be using the decimal type instead of double.
Read The Floating-Point Guide to understand why.

Formatting a decimal number similar to ToString("G29") plus a thousands separator

I need to display some numbers in a variable of type decimal.
I want to display them almost as they are, which ToString("G29") gives me.
However, I want to add a thousands separator. ToString("N") gives me the thousands separator but totally loses the "G29 goodness".
Is there a simple solution to get the display string I want?
value "N" "G29" What I Want
============= ========== ========== ==============
296018.413 296,018.41 296018.413 296,018.413
652609 652,609.00 652609 652,609
296.018413 296.02 296.018413 296.018413
326.305 326.31 326.305 326.305
Edit:
Another SO question/answer recently made me aware that "G29" returns values less than 0.0001 in scientific notation. So when I wrote the question I was unaware that the solution needed to handle special cases like these:
value What I Want
============ =============
0.00001 0.00001
12345.000067 12,345.000067
You might have to do a little bit of work around.
How about this?
decimal d = 34561.2223400M;
string decimalPart = (d - (int)d).ToString("G29");
string integerPart = d.ToString("##,###");
string finalNumber = integerPart + decimalPart.Substring(1,decimalPart.Length-1);;
There is a pretty simple solution to this, though it involves a fairly long format string.
decimal d = 12345.000067m;
string s = d.ToString("#,###0.############################"); // 28 #'s after the decimal
You have to format the string.
Try:
string yourString = String.Format("{0:N29}", yourWeight);
Edit:
The above was pretty close. This gives exactly the desired results:
string yourString = String.Format("{0:N29}", yourWeight).Trim(new [] { '0', '.' });

C# convert string to decimal 4dp

I need to take a string object and convert it to a decimal to 4 dp.
So for example:
string val = "145.83011";
decimal sss = Math.Round(Convert.ToDecimal(val), 4);
bring back 145.8301 - good
However:
string val = "145.8300";
decimal sss = Math.Round(Convert.ToDecimal(val), 4);
brings back 145.83
I need it to be 145.8300
I need it in a decimal format so can't use string format options.
Thanks
rob
One option would be to use string manipulation three times:
Parse the original text to a decimal value (this will preserve the original number of decimal places)
Use string formatting to end up with a string with exactly 4 decimal places. (Math.Round ensures there are at most 4DP, but not exactly 4DP.)
Parse the result of the formatting to get back to a decimal value with exactly 4DP.
So something like this:
public static decimal Force4DecimalPlaces(string input)
{
decimal parsed = decimal.Parse(input, CultureInfo.InvariantCulture);
string intermediate = parsed.ToString("0.0000", CultureInfo.InvariantCulture);
return decimal.Parse(intermediate, CultureInfo.InvariantCulture);
}
I recoil from using string conversions like this, but the alternatives are relatively tricky. You could either get the raw bits, split out the different parts to find the mantissa and scale, then adjust appropriately... or you could potentially work out some sequence of arithmetic operations to get to the right scale. (Jeppe's approach of multiplying by 1.0000m may well be entirely correct - I just don't know whether it's documented to be correct. It would at least be worth adding in appropriate tests for the sorts of numbers you expect to see.)
Note that the above code will perform round up on halves, as far as I can tell, so 1.12345 will be converted to 1.1235 for example.
Sample with output in comments:
using System;
using System.Globalization;
class Test
{
static void Main()
{
Console.WriteLine(Force4DecimalPlaces("0.0000001")); // 0.0000
Console.WriteLine(Force4DecimalPlaces("1.000000")); // 1.0000
Console.WriteLine(Force4DecimalPlaces("1.5")); // 1.5000
Console.WriteLine(Force4DecimalPlaces("1.56789")); // 1.5679
}
public static decimal Force4DecimalPlaces(string input)
{
decimal parsed = decimal.Parse(input, CultureInfo.InvariantCulture);
string intermediate = parsed.ToString("0.0000", CultureInfo.InvariantCulture);
return decimal.Parse(intermediate, CultureInfo.InvariantCulture);
}
}
Both Convert.ToDecimal and decimal.Parse do preserve trailing zeroes in the string (a System.Decimal can have at most 28-29 digits in total, so in most cases there's still room for all the trailing zeroes).
And Math.Round(..., 4) preserves trailing zeroes up to the fourth place after the decimal period.
Therefore the premise of the question is wrong. Your example does bring back what you want.
In any case, consider specifying the overload that takes in an IFormatProvider as well, and give CultureInfo.InvariantCulture as argument. Then the conversion is independent of the local culture.
If instead you want to handle strings like "145.83" and append trailing zeroes that were not in the string, use:
string val = "145.83";
decimal sss = Math.Round(
decimal.Parse(val, CultureInfo.InvariantCulture) * 1.0000m,
4);
Epilog: If you don't like multiplying and dividing by numbers like 1.0000m, use decimal.GetBits to get the internal representation. Adjust the integer "part" by multiplying or dividing by the appropriate power of ten, and adjust the scale "part" by subtracting or adding the corresponding number. The scale counts the number of places to move the decimal point to the left, starting from the 96-bit integer.

Convert a string to double

I need help converting a string to double with 7 decimals. I have a string "00000827700000" and need it converted to 82.77
Tried using String.Format() with {0:N7} without success.
It looks like you could use:
decimal x = decimal.Parse(text.Substring(0, 7) + "." +
text.Substring(7),
CultureInfo.InvariantCulture);
That would actually parse it to 82.7700000, as decimal preserves trailing zeroes (to an extent) but maybe that's good enough? It not, you could change the second argument to
text.Substring(7).TrimEnd('0')
Note that I'd strongly recommend you to at least consider using decimal instead of double. You haven't explained what this value represents, but if it's stored as decimal figures which you need to preserve, it smells more like a decimal to me.
Based on the edit, it could be simplified as
var text = "00000827700000";
var x = decimal.Parse(text, CultureInfo.InvariantCulture) / 10000000;
Console.Write(String.Format("{0:N7}", x));

C# Get exact string formation from 'double' type

As I'm working on C#, I have one field named 'Amount'.
double amount = 10.0;
So, I want the result like '10.0' after converting it to string.
If my value
amount = 10.00, then I want result '10.00' after converting it to string.
So, Basically I want exact result in string as it is in double type. (With precisions).
Thanks in advance.
string result = string.Format( "{0:f2}", amount );
What you ask is not possible. A double in C# is a simple 64-bit floating-point value. It doesn't store precision. You can print your value with one decimal places, or two, as other answers describe, but not in a way that's "preserves" the variable's original precision.
string amountString = amount.ToString("N2");
"N2" is the format string used as the first parameter to the .ToString() method.
"N" stands for number, and 2 stands for the number of decimal places.
More on string format's here:
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
As #Michael Petratta points out, double doesn't carry with it the precision of the input. If you need that information, you will need to store it yourself. Then you could reconstuct the input string doing something like:
static public string GetPrecisionString( double doubleValue, int precision)
{
string FormattingString = "{0:f" + precision + "}";
return string.Format( FormattingString, doubleValue);
}

Categories