Can't find simple way to convert double to string. I need to convert large numbers without distortion. Such as:
double d = 11111111111111111111;
string s = d.ToString();
Console.WriteLine(s);
//1.11111111111111E+19
How to get string value from double value exactly the same as user enter.
11111111111111111111111 => "11111111111111111111111"
1.111111111111111111111 => "1.111111111111111111111"
Any ideas how it can be done?
double is a floating point type. So it has a limited accuracy. In your example, you could do something like this:
double d = 11111111111111111111;
string s = d.ToString("F0");
Console.WriteLine(s);
But as you'll see,this would output 11111111111111100000 instead of 11111111111111111111,so it has lost accuracy in the process. So the answer here is use the right type for the work. If you need a string, use a string variable to store the value.
Edit
This was the question i was trying to find that explains the problem with floating point math., thanks to #GSerg
First of all: 11111111111111111111111 is to large for a double value and also this value: 1.111111111111111111111 since the double max decimal length is 17.
By default, a Double value contains 15 decimal digits of precision,
although a maximum of 17 digits is maintained internally.
For this reason you should use BigInteger and then ToString for formatting the output.
There is also a library in the nuget Directory called BigRational, never used and seems in Beta stage but probably will help in solving this problem.
In general case, you can't do this: user can well input, say 123, in many a way:
123
123.00
1.23e2
12.3E1
123.0e+00
1230e-1
etc. When you convert the user input into double you loose the initial format:
string userInput = ...
// double is just 123.0 whatever input has been
double value = double.Parse(userInput);
In case you want to drop exponent if it's possible you can
double value = 11111111111111111111;
string result = value.ToString("#######################");
And, please, notice, that double has 64 bit to store the value, that's why a distortion is inevitable for large numbers:
// possible double, which will be rounded up
double big = 123456789123456789123456789.0;
// 1.2345678912345679E+26
Console.WriteLine(big.ToString("R"));
// 123456789123457000000000000
Console.WriteLine(big.ToString("###########################"));
May be you want BigInteger instead of double:
using System.Numerics;
...
BigInteger value = BigInteger.Parse("111111111111111111111111111111111");
// 111111111111111111111111111111111
Console.WriteLine(value.ToString());
Related
anyone knows how to add two float numbers with currency sign and place the sum into a dataGridview cell?
this is my code:
private void button8_Click(object sender, EventArgs e)
{
double a =0.70;
double b = 0.50;
dataGridView2.Rows[0].Cells[1].Value = "£" + (a+b);
}
if I declare a and b as float it gives error.
if I declare a and b as Double, the result is £1.2 as shown in photo but NOT £1.20 .
I made column 1 properties to contain a currency value ( result = £1.2)
I made column 1 properties to contain a numeric value and the result is same.
how can I make it £1.20?
is there any way to do it?
thank you
The double type doesn't keep track of how many decimal places were there when the result was computed. As far as it is concerned, 1.2 and 1.20 and 1.200 are all the same value.
You want a specific string representation of that number, with exactly two decimal places. The easiest way to get the desired string representation is using a format string. For example, you can do this:
(a + b).ToString("0:00");
In cases where you want to format multiple expressions, you may find this alternative more convenient:
string.Format("{0:0.00} {1:0.00} {2:0.0}", a, b, a + b)
Keep in mind that float and double are tricky. You probably want to handle money using the decimal type instead.
You can use:
dataGridView2.Rows[0].Cells[1].Value = (a + b).ToString("'£'0.00"));
To do this, you need to set a format for the string. Try using this:
dataGridView2.Rows[0].Cells[1].Value = string.Format("£{0:0.00}", a + b)
You can try this:
dataGridView2.Rows[0].Cells[1].Value = "£" + (a+b).ToString("0.00");
Thank you all for your help. now it is solved. I played around with cell format type and suddenly it changed to £1.20.
Definitely keep in mind the explanations given by Theodoros, especially the suggestion to use the decimal type.
That said, an alternative is to use a System.Globalization.CultureInfo. This has the advantage of correctly handling the symbol, decimal digits, decimal separator, group separator, and group sizes. This way you see results such as £1,234,567.89 instead of £1234567.89.
CultureInfo gb = new CultureInfo("en-GB");
string result = (a + b).ToString("c", gb.NumberFormat);
A further advantage is that parsing out the original value is just as easy:
decimal amount = Decimal.Parse(result, NumberStyles.Currency, gb);
I have a string that can be up to 9 characters long including an optional decimal point but all the others will be numbers. It could be "123456789" or "12.345678", for example.
What variable type should I convert it to so that I can use it in calculations?
And how do I do that?
float.Parse("12.345678");
or
float.Parse("12.345678", CultureInfo.InvariantCulture.NumberFormat);
For avoiding these kind of outputs:
1.524157875019e+16
8.10000007371e-9
For integers you can checkout this link also: https://msdn.microsoft.com/en-us/library/bb397679.aspx
You should convert it to float, double or decimal, depending on how big the numbers become.
You can use Parse() or TryParse() to parse a string to an arithmetic type.
string numberString = "123456789";
double number;
if (!double.TryParse(numberString, out number))
{
// There was an error parsing ...
// Ex. report the error back or whatever ...
// You can also set a default value for it ...
// Ex. number = 0;
}
// Use number ...
It's a question of precision and a bit of memory consumption.
if the floating point remainder is important to you use one of the following:
float - 4 bytes, 7 digits precision
Double - 8 bytes, 15-16 digits precision
Decimal - 16 bytes , 28-29 digits precision
How to read figure without any symbol??
example -8759.328 and 8569.659"
output should be 8759.32 and 8569.65 in double
var debit = txtDebit.Text.Split('-');
oBankPages.DebitAmount = Convert.ToDouble(debit);
If I understand, you have two strings,
var numberStringOne = "-8759.328";
var numberStringTwo = "8569.659";
If you want to treat these strings like decimals, first you must parse them.
var numberOne = decimal.Parse("-8759.328");
var numberTwo = decimal.Parse("8569.659");
Next, you could get the value ignoring the sign, by using Math.Abs, Abs. being an abbreviation of Absolute.
var numberOne = Math.Abs(numberOne);
Then you convert the number back to a rounded string using the appropriate format specifier.
var formattedNumberOne = numberOne.ToString("D2");
or perhaps
Console.WriteLine("{0:D2}", numberTwo);
so, all on one line.
var formattedNumberOne = Math.Abs(decimal.Parse("-8759.328")).ToString("D2");
Formatting can be done only with strings integral and floating point types doesn't have any formatting by thier own
var res = Math.Abs(-8759.328).ToString("f2");
If at all you need the result as Double you can Round the result
var res = Math.Round(Math.Abs(-8759.328), 2);
Note: above calls Math.Round so result will be rounded rather than formatted. In other words you may get result as 8759.33 instead of 8759.32
oBankPages.DebitAmount = Math.Abs(Convert.ToDouble(txtDebit.Text));
Beware that fractions like these cannot be accurately represented in floating point.You can simply solve it out in your case.
double value = Math.Truncate(100 * Math.Abs(-8759.328)) / 100;
OUTPUT : 8759.32
Try this.
string debit = Regex.Replace(txtDebit.Text, "[^0-9^.]+", "");
oBankPages.DebitAmount = Math.Abs(Convert.ToDouble(debit)).ToString("f");
Use decimal instead of double. Your data is related to money. Even one cent off is significant. You cannot afford to use floats or doubles, as they are lossy data types that remember only the "beginning" of the number and forget the ending. decimal is designed to be precise. If you ever work for financial sector, remember: no floats, no doubles. Of course unless some high-accountant orders tells you they level it up somehow and it's safe due to their creativity..
Read about Salami Attack
I want to convert float value to string.
Below is the code which i am using for the conversion.
static void Main(string[] args)
{
string s =string.Format("{0:G}", value);
Console.Write(s);
Console.ReadLine();
}
and it outputs as 2.5
But my problem is i want to get the value as 2.50 because i want to compare it with original value later in my project.
so please suggest me if there are any ways to do it?
You should be using {0:N2} to format to two decimal places.
string.Format("{0:N2}", 2.50)
For 3 decimal places:
string.Format("{0:N3}", 2.50)
And so on.
You can also store the value in a string this way without worrying about precision and then convert your value where you are testing for comparison as string:
string strDecimalVal = Convert.ToString( 2.5000001);
because i want to compare it with original value later in my project.
...then you will need to store the number of decimal places the original value had. Once the value is a float, this information is lost. The float representations of 2.5, 2.50 and 2.500 are exactly the same.
So, basically, you have the following possibilities (in order of preference):
Don't do a string comparison between the old and the new value. Convert both values to float and then compare them (with a margin of error since floats are not precise).
Store the number of decimal places of the old value and then use myFloat.ToString("F" + numDecimals.ToString()) to convert it to a string.
Store the value as a string instead of a float. Obviously, you won't be able to do math on that value.
Alternatively, if you do not insist on using floats, decimals might suit your purpose: The do store the number of significant digits:
decimal x = Decimal.Parse("2.50", CultureInfo.InvariantCulture);
decimal y = Decimal.Parse("2.500", CultureInfo.InvariantCulture);
Console.WriteLine(x.ToString()); // prints 2.50
Console.WriteLine(y.ToString()); // prints 2.500
Try this
Console.WriteLine("{0:F2}", 2.50);
Console.WriteLine("{0:0.00}", 2.50);
Console.WriteLine("{0:N2}", 2.50);
Version 1 and 2 are almost similar, but 3 is different. 3 will include number separators when number is large.
For example the following outputs 454,542.50
Console.WriteLine("{0:N2}", 454542.50);
More on MSDN
On my system, the following code prints '3.6':
double a = 1.2;
int b = 3;
double c = a * b;
Console.WriteLine(c);
But in the debugger, I can see that c has a value with more than 2 digits:
I know that I can display the full representation with Console.WriteLine("{0:R}", c). Is this the only and recommended way to display the actual value of a double?
update
Going with the above example, I'd like to print c such that if the user were to take the printed value and insert that back into the code in a test using ==, the comparison would be true. In this case c == 3.5999999999999996 returns true.
Console.WriteLine calls Double.ToString which uses the the "G" format specifier. This uses the current culture to determine the number of decimal places (1 for "en-US").
If you want to display 8 decimal places you can use the numeric format specifier:
Console.WriteLine(c.ToString("N8"));
Standard Numeric Format Strings
Edit: The debugger uses this method to convert a double to a string:
_ecvt_s
I assume it's the cheapest way to convert it.
Where i have found it: How does Visual Studio display a System.Double during debugging?
3.999999999999996 is not the actual value of the double either; that's just the value rounded off to fifteen places or whatever. There is no built-in way to display the actual exact value that the double is representing. This is really too bad, because every normal double can be represented exactly as a decimal string, and it would be nice to be able to see that.
As a public service, I've put source code for a device which does that on my blog:
http://ericlippert.com/2011/02/17/looking-inside-a-double/
Note that it uses the Rational class from Microsoft Solver Foundation. If you don't have that then you can either download it for free, or write your own Rational class; it's character-building to do so.
If the subject of how doubles work internally interests you, consider checking out my archive of handy articles explaining all that. It's at:
http://blogs.msdn.com/b/ericlippert/archive/tags/floating+point+arithmetic/
Start from the bottom; those are in reverse-chronological order.
You could also use a different approach for example if you want to return 2 decimal places you could try something like this
double a = 1.2;
int b = 3;
double c = a * b;
var s = string.Format("{0:0.00}", c);
Console.WriteLine(s);
Output = 3.60
if you want to suppress the last 0 where out put is 3.6 you could do
var s = string.Format("{0:0.##}", c);
Output = 3.6 feel free to play around with it
double a = 1.2;
int b = 3;
double c = a * b;
string formatted = c.ToString("N5");
Console.WriteLine(formatted);