Round off in listview - c#

I am trying to round off each row to the nearest 1.0 in a column of a listview, so meaning 1.58 should show 2.00 and 1.48 should be 1.00 -
Math.Round(listView1.Columns[2].ToString(), 10);

You need to use 0 in digits parameter. You expect no digits here, but you're passing 10 to digit parameter which says to round with 10 digits after decimal.
var res = Math.Round(1.58, 0);//2
var res = Math.Round(1.48, 0);//1
Just saw you try to Round the string, You'll have to convert it to Double or decimal or whatever.
var rounded = Math.Round(Double.Parse(listView1.Columns[2].ToString()), 0);

In case you want to get String as a final result (as far as you've put ToString() in your code), you may just use appropriate formatting string ("F0" in your case):
String result = (1.58).ToString("F0"); // <- "2"
...
String result = (1.48).ToString("F0"); // <- "1"

You can't round a string directly.
string val=listView1.Columns[2].ToString();
double i;
if(Double.TryParse(val, out i))
{
Console.WriteLine(Math.Round(i)); // you can use Math.Round without second
// argument if you need rounding to the
// nearest unit
}

Related

Decimal rounding issues

I have a scenario in which some variable values have decimal values, the values can have leading .0, .234, .124, .125, numbers like this, and so on. If the number has leading decimal and zero it should ignore and if a number has leading 3 or more numbers it should round off to two.
Let's say the code is as follows:
var anone = "23"
var antwo = "23.0"
var anthree = "23.467"
var anfour = "23.125"
In order to remove the leading decimal and zero I have used the following method:
var removingzero = antwo.Replace(".0", "");
// The result will be = 23
In order to round off and limit the number to two decimal points I have used the following method:
var convertodecimal = Decimal.Parse(anthree);
var roundtotwo = Math.Round(convertodecimal, 2);
// The result will be = 23.47
similarly in order to convert the last one I follow the same method:
var convertodecimal = Decimal.Parse(anfour);
var roundtotwo = Math.Round(convertodecimal, 2);
// The result will be = 23.12
// But the Result should be = 23.13
So, the problem is when I am trying to round off any number like the last example it does not do it, how can I fix it.
It sounds like your question is a long way of asking "How can I force rounding UP when a decimal number ends in 5?"
If that's the case, then you can use the overload of Math.Round that takes a MidpointRounding argument, and specify either MidpointRounding.AwayFromZero or MidpointRounding.ToPositiveInfinity.
The behavior of these is the same for positive numbers, but difference is seen with negative numbers, where -23.125 will round to -23.13 if AwayFromZero is specified, or -23.12 if ToPositiveInfinity is specified.
So your code might look like this instead:
var roundtotwo = Math.Round(convertodecimal, 2, MidpointRounding.AwayFromZero);
Try by changing your Math.Round() to below one:
Math.Round(num,2, MidpointRounding.AwayFromZero)

Floor behavior with number 1.9999999999999999d [duplicate]

This question already has answers here:
Why does floating-point arithmetic not give exact results when adding decimal fractions?
(31 answers)
Closed 5 years ago.
Look at this situation:
var number1 = Math.Floor(1.9999999999999998d); // the result is 1
var number2 = Math.Floor(1.9999999999999999d); // the result is 2
In a both cases, the result should be 1. I know it's a very unlikely scenario, but possible to occur. The same ocurr with Math.Truncate method and (int) cast.
Why does it happen?
There is no exact double representation for a lot of numbers.
The double number the nearest from 1.9999999999999999 is 2, so the compiler rounds it up.
Try to print it before using your Math.Floor function !
However, the nearest from 1.9999999999999998 is still 1.something, so Floor gives out 1 .
Again, it would be enough to print the number before the function Floorto see that they were actually not anymore the one entered in the code.
EDIT : To print out the number with most precision :
double a1 = 1.9999999999999998;
Console.WriteLine(a1.ToString("G17"));
// output : 1.9999999999999998
double a2 = 1.9999999999999999;
Console.WriteLine(a2.ToString("G17"));
// output : 2
Since double precision is not always precise to 17 significative digits (including the first one before the decimal point), default ToString() will round it up to 16 significant digits, thus, in this case, rounding it up to 2 as well, but only at runtime, not at compile time.
If you put literals values into another variables, then you see it why:
var a1 = 1.9999999999999998d; // a1 = 1.9999999999999998d
var number1 = Math.Floor(a1);
Console.WriteLine(number1); // 1
var a2 = 1.9999999999999999d; // a2 = 2
var number2 = Math.Floor(a2);
Console.WriteLine(number2); // 2
As for why - this has to be something to do with precision of double and decision of compiler as to what value to use for a given literal.

How can I force a number to have 3 digits while keeping ALL decimal places?

In c#, I want to force 0s when converting from double to string in case a number is lower than 100, the only challenge is that I want to keep all decimal places. Examples
58.3434454545 = 058.3434454545
8.343 = 008.343
I tried with ToString + a format provider but I'm not certain what's the correct provider for keeping all decimal places
You can use formatter strings for .ToString(), documented here.
To do what you want you can use this as example, noting the maximum digits for double is 17:
double numberA = 58.3434454545;
numberA.ToString("000.##############"); //058.3434454545
double numberB = 8.343;
numberB.ToString("000.##############"); //008.343
This is a rather ass ugly solution but if you wanted the number of decimals to be dynamic you could try something like this:
private string FormatDouble(double dbl)
{
int count = BitConverter.GetBytes(decimal.GetBits((decimal)dbl)[3])[2];
var fmt = string.Concat("000.", new string('#', count));
return dbl.ToString(fmt);
}
Call it like this:
Console.WriteLine(FormatDouble(58.3434454545123123));
Console.WriteLine(FormatDouble(8.3431312323));
And your output would be this:
058.3434454545123
008.3431312323
I'm sure there is a much better way to do this and I'm not sure about performance, but hey it works and you don't have to guess the number of decimals you need, so that's a plus

Digit grouping with two decimal places in c#

I want to display a number which is of double datatype in C#, in grouped digits and with two decimal places only if it contains a decimal no.
e.g. If there is 2000.4567 and 2000.45, it must be displayed as 2,000.45 and if it is 2000 then it will displayed as 2,000 (grouped but without decimal).
I have tried this and it is working fine for digit grouping but it rounds off the decimal no. to an integer value either by floor or ceil:
DimensionLength.ToString("#,##0")
DimensionLength is of type double.
Try this Code
double s=123.345345;
string str=string.Empty;
str = s.ToString("#,0.##");
MessageBox.Show(str);
I think you are better off by creating your own custom condition
double _inputval=2000.4567
string _outputVal="";
if ((_inputval % 1) == 0)
{
_outputVal = _inputval.ToString("#,##");
}
else
{
_outputVal = _inputval.ToString("N2");
}
Hope it helps

C# format a double with ToString, and dispay zero value

I'm trying to find the best way to display a double in C# as follows:
7.345 should display as "73"
100.0 should display as "100"
0.234 shoud display as "02"
The input is a value between 0.00 and 10.00. I need to convert it to a filename. E.g. in case of a value of 5.4234, I should display "img54.jpg".
The problem is that I can't figure out how to display zero values in ToString() of doubles.
I tried this:
(10 * 7.345).ToString("##.") => correct
(10 * 10.00).ToString("##.") => correct
(10 * 0.000).ToString("##.") => FAIL, doesn't display anything.
(10 * 0.000).ToString("D2") => FAIL, D is not allowed in doubles
I can of course do some sophisticated string building, but if it's possible to use ToString, that would be much better of course.
Anyone an idea?
What do you want 0.00 to display as? "00"?
In that case you can try with format ToString("00.") instead.
Can you simply check if the double is 0? and If it is, set img00.jpg to your filename. That seems a lot easier than reworking your algorithm.
Why don't you convert it to an int?
int result = (int)(input * 10.00);
return result.ToString();
You could just convert to int before formatting like this:
((int)(10 * 7.345)).ToString("D2")
If you always have the input number of this format: #.###
You can multiply it by 1000 and divided by 100 and cast the result to an integer.
7.345 * 1000 = 7345 / 100 = 73.45 => Convert.ToInt32 => 73
0.000 * 1000 = 0 / 100 = 0 => Convert.ToInt32 = 0
Or you can multiply by 10 and convert to Integer.
return ((int)(input * 10.00)).ToString().SubString(0, 2);
double val = 7.345;
string result = val.ToString("0.#").Replace(".","");

Categories