How to read figure without any symbol? - c#

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

Related

how to leave decimal places to 1 without rounding

I need to convert my value 2.8634 to 2.8. I tried the following ,
var no = Math.Round(2.8634,2,MidpointRounding.AwayFromZero)
I'm getting 2.87.
Suggest me some ideas how to convert.
Thanks
This might do the trick for you
decimal dsd = 2.8634m;
var no = Math.Truncate(dsd * 10) / 10;
Math.Truncate calculates the integral part of a specified decimal number. The number is rounded to the nearest integer towards zero.
You can also have a look on the difference between Math.Floor, Math.Ceiling, Math.Truncate, Math.Round with an amazing explanation.
Use this one.Hope this will work for you.
var no = Math.Round(2.8634,1,MidpointRounding.AwayFromZero)
It's a tad more cryptic (but more efficient) than calling a Math method, but you can simply multiply the value by 10, cast to an integer (which effectively truncates the decimal portion), and then divide by 10.0 (or 10d/10f, all just to ensure we don't get integer division) to get back the value you are after. I.e.:
float val = 2.8634;
val = ((int)(val * 10)) / 10.0;

Get string from large double value(C#)

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());

How to add two float numbers with currency sign?

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);

Rounding to 2 decimal places c#

Currently have a working rounding model within my c# code and is perfectly rounding numbers that have more than 2 decimal places down to 2 decimal places which is great. However, when i have lets say double value = 100.6, and i put that into double dollar_value = Math.Round(value, 2), it still returns as 100.6.
I was wondering if there was a way to transform a 1 decimal place value to 2 decimal places?
Numbers are not stored with extra zeroes (As it is a waste of memory to do so, being the numbers are the same with or without). In order to represent a number this way you will either need to display or store it as a string.
string str = value.ToString("#.00", CultureInfo.InvariantCulture);
Now str will always have 2 decimal places.
I don't know the C# method, but in C++ I'd use one of these two methods:
double value = 23.666666 ; // example
value = 0.01 * floor ( value * 100.0 ) ; // There's a "floor" function in C# too
^ See https://msdn.microsoft.com/en-us/library/e0b5f0xb(v=vs.110).aspx
Or
double value = 23.666666 ; // example
value = 0.01 * (double) ( (int)(value*100.0) ) ;
Or
double value = 23.666666 ; // example
value = 0.01 * double ( int ( value*100.0 ) ) ; // same as previous, but more C++ like
The other answers are probably better if you're looking to "print a dollar amount with two decimal places." However, if you want to transform the number to use internally, this is a way to do it.
If you want the string representation to have two decimal points use:
yourNumber.ToString ("0.00");
The number itself is always stored as a ~29 digit number regardless of its string representation.
Your value just needs to be formatted when it's display - for example value.ToString("N2") will convert it to a string with two decimal places. Check out the Standard Numeric Format Strings on MSDN to see a broader list of formatting strings.
Additionally, I'd only convert to a string when you're ready display the value to a user and would keep it as a numeric type (e.g. double) if you're passing it around between methods or planning to do any further calculations on it. Otherwise you'll be unnecessarily converting the value to and from a string multiple times.

parse float from string

I have some problem with parsing float value from string.
Problem is with decimal part of value, here is example:
var tmp = "263148,21";
var ftmp = float.Parse(tmp); //263148.219
I tried some other values, but I don't figured out, from what reason are some decimal values incorrect.
This doesn't have anything to do with the comma in the OP's code - instead, this question is about a float value not accurately representing a real number.
Floating point numbers are limited in their precision. For really precise numbers you should use double instead.
See also this answer: why-is-floating-point-arithmetic-in-c-sharp-imprecise? and have a look at this for more information: What Every Computer Scientist Should Know About Floating-Point Arithmetic
var tmp = "263148,21";
var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.NumberFormat.NumberDecimalSeparator = ",";
var ftmp = double.Parse(tmp, culture);
You have to use double instead of float
As stated in other answers and comments, this is related to floating point precision.
Consider using Decimal if you need to have the exact same decimals or to leverage rounding errors. But please note that this type is much more heavy weight (128 bits) and might not be suited for your case.
var tmp = "263148,21";
var dtmp = Decimal.Parse(tmp); //263148.21

Categories

Resources