double a =(80/100);
lbl1.Text = a.ToString();
answer is display as 0 why ?
how to get correct answer?
the expression (80/100) evaluates to 0 because 80 and 100 are both interpreted as int, and int divided by int always results in an int. What you need is this:
double a =(80d/100d);
lbl1.Text = a.ToString();
That way the expression uses double values and you get what you expect - 0.8.
Related
I'm trying to write this in C#. The requirement is very straightforward - check if a string input is a value within the range from 0 to 100.
I want to make sure the string is either an integer value in the range of 0 to 100 or
a double that's within the same range as well.
So for example, these are the accepted values:
0
50
100
0.1
50.7
100.0
I checked the double.parse method here but not sure if it's the one I'm looking for: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-7.0#system-double-tryparse(system-string-system-iformatprovider-system-double#)
The reason is that it can also parse string like this one: 0.64e2 (which is 64)
Is this something that can be achieved with built-in library already?
Wrote you a little snippet:
// C# function to check if string is a percentage between 0 and 100
public static bool IsPercentage(string s)
{
// regex check if s is a string with only numbers or decimal point
if (Regex.IsMatch(s, #"^\d+\.?\d*$"))
{
double d = Convert.ToDouble(s);
return d >= 0 && d <= 100;
}
return false;
}
Also returns false if the string contains % or has exponential (e).
if my understanding of the Q was correct and exponential representations like mentioned "0.64e2" is unwanted:
static bool IsPercentage(string s)
{
if (Single.TryParse(s, NumberStyles.AllowLeadingSign |
NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out Single n))
return n >= 0 && n <= 100;
return false;
}
I'm not sure if I should ask this, but the details might help on finding out :p
I have a table like this
And I'm using compute to get the interval where a double variable stands in the Variavel column
double value = 6;
double max Convert.ToDouble(DataAccess.Instance.tabela1vert0caso1W.Compute("MIN(Variavel)", "Variavel >= " + value.ToString(CultureInfo.InvariantCulture)));
double min = Convert.ToDouble(DataAccess.Instance.tabela1vert0caso1W.Compute("MAX(Variavel)", "Variavel <= " + value.ToString(CultureInfo.InvariantCulture)));
The problem here is that I get the inifity error on the double min line, however it only happens when I'm between 5 and 15, if I choose any other value, i get the program to work properly.
Any hint?
By the way I checked the value of value just before the lines, and it's still 6.
I'm not sure what the actual problem is, however, you could always use Linq-To-DataTable which is more powerful (supports the whole .NET framework) and also more readable:
var variavels = DataAccess.Instance.tabela1vert0caso1W.AsEnumerable()
.Select(row => row.Field<int>("Variavel"));
double max = variavels.Where(d => d >= value).Max();
double min = variavels.Where(d => d <= value).Min();
Its possible for the compute method to return DBNull.Value. It seems unclear when if at all the Max() function will return this, but possibly your select returns 0 rows?
I suggest you add a check for DBNull.Value and set min to value when it occurs
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
}
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(".","");
I'm going through my code and each time D1 ends up being NaN. The code looks fine to me, and I'm completely stumped...
double D1;
Data Data = new Data();
PriceSpot = 40;
Data.PriceStrike = 40;
Data.RateInterest = .03;
Data.Volatility = .3;
Data.ExpriationDays = 300;
D1 =
(
Math.Log(PriceSpot/Data.PriceStrike) +
(
(Data.RateInterest + (Math.Pow(Data.Volatility,2)/2)) *
(Data.ExpirationDays/365)
)
) /
(
Data.Volatility *
Math.Pow(Data.ExpirationDays/365,.5)
);
Data.Volatility * Math.Pow(Data.ExpirationDays/365,.5) is 0 since 300/365 as int equals to 0
Assuming ExpriationDays property is of type int indeed, it'll make the whole expression be 0.
For example:
[Test]
public void Test()
{
var val = 300 / 365;
Assert.That(val, Is.EqualTo(0));
}
Some comment about dividing by 0:
When dividing two 0 integers an exception will be thrown at runtime:
[Test]
public void TestIntDiv()
{
int zero = 0;
int val;
Assert.Throws<DivideByZeroException>(() => val = 0 / zero);
}
When dividing two 0 doubles the result will be NaN and no exception will be thrown:
[Test]
public void TestDoubleDiv()
{
double zero = 0;
double val = 0 / zero;
Assert.That(val, Is.NaN);
}
Check the type of Data.ExpirationDays, it may be that Data.ExpirationDays/365 is evaluating as 0 if the type is integral. That would mean the denominator would be zero (the square root of zero is zero and zero multiplied by Data.Volatility is still zero) which would lead to a problem.
In fact the numerator turns out to be zero in your case as well since logn1 is always zero and you're adding that to zero (another value which is multiplied by Data.ExpirationDays/365).
You may want to consider using floating point types throughout the process.
Data.ExpirationDays/365 is equal to zero.
0 ^ 0.5 is equal to zero too.
Data.Volatility * 0 = 0.
D1 = Something / 0.
So NaN is quite expected.
Is it because you've mis-spelled Data.ExpirationDays as Data.ExpriationDays so Data.ExpirationDays is defaulted to 0? This would give 0/0 ie NaN (numerator is 0 b/c you happen to have strike=spot)
( I've never used C# so am not sure whether this is only an error in your posting or in your code (which I would have expected the compiler to catch) )