private void txtFinal_Leave_1(object sender, EventArgs e)
{
int prelim;
int midterm;
int final;
decimal average;
string remarks;
prelim = int.Parse(txtPrelim.Text);
midterm = int.Parse(txtMidterm.Text);
final = int.Parse(txtFinal.Text);
average = (prelim + midterm + final) / 3;
txtAverage.Text = average.ToString();
if (average >= 75)
{
remarks = "passed";
}
else
{
remarks = "failed";
}
txtRemarks.Text = remarks;
// this is the output 83 passed
// I want to be like this 83.25 passed
}
average = (prelim + midterm + final) / 3.0m;
This will fix your problem.
Int is an integer type; dividing two ints performs an integer division, i.e. the fractional part is truncated since it can't be stored in the result type (also int!). Decimal, by contrast, has got a fractional part. By invoking Decimal.Divide, your int arguments get implicitly converted to Decimals.
You can enforce non-integer division on int arguments by explicitly casting at least one of the arguments to a floating-point type, e.g.: 3.0m this is casting to decimal !
please upgrade your code as follow:
average = Convert.ToDecimal(prelim + midterm + final) / 3;
txtAverage.Text = string.Format("{0:0.00}", average);
Related
Just a simple console program in c#. The answer is always 1, but I want to get the right answer and the answer to always be an integer, nothing but whole numbers here.
Console.Write("Ange dagskassa (kr): ");
string inlasning = Console.ReadLine();
int dagskassa = int.Parse(inlasning);
Console.Write("Ange nuvarande lunchpris (kr): ");
string inlasning2 = Console.ReadLine();
int lunchpris = int.Parse(inlasning);
double antalGaster = dagskassa / lunchpris;
Console.WriteLine("Antal gäster: " + antalGaster + "st.");
The problem here is that you're converting the same number twice, to two different variables, and then dividing them, so the answer will always be 1:
int dagskassa = int.Parse(inlasning);
int lunchpris = int.Parse(inlasning); // You're parsing the same input as before
To resolve this, convert the second input for the lunch price:
int dagskassa = int.Parse(inlasning2); // Parse the *new* input instead
You'll need to cast your ints to double in order for the above to work. For example,
int i = 1;
int j = 2;
double _int = i / j; // without casting, your result will be of type (int) and is rounded
double _double = (double) i / j; // with casting, you'll get the expected result
In the case of your code, this would be
double antalGaster = (double) dagskassa / lunchpris;
To round to the lowest whole number for a head count, use Math.Floor()
double antalGaster = Math.Floor((double) dagskassa / lunchpris);
I am receiving an error "Operator '*' cannot be applied to operands of type 'int' and 'decimal[]'", as I am attempting to multiply two values with different data types (one being a value located in an array). My question is how am I able to multiple numberOfMinutes * perMinuteRate in my code below? My variable is called total, which I declared a double data type (although may be incorrect).
I tried changing data types and played with formatting (like ToString), but I am not sure what to do. I also tried to google the answer with no success.
I am by no means a professional programmer; I'm not in school. I'm a data analyst who is learning to program.
Here is my code:
static void Main(string[] args)
{
int[] areaCodes = { 262, 414, 608, 715, 815, 920 };
decimal[] perMinuteRate = { .07m, .1m, .05m, .16m, .24m, .14m };
int numberOfMinutes;
int userAreaCode;
string inputString = "1";
while (inputString != "0")
{
int x;
Console.WriteLine("Enter the area code for your call (or 1 to end):");
inputString = Console.ReadLine();
userAreaCode = Convert.ToInt32(inputString);
Console.WriteLine("How many minutes will your call last?");
inputString = Console.ReadLine();
numberOfMinutes = Convert.ToInt32(inputString);
for (x = 0; x < areaCodes.Length; x++)
{
if (userAreaCode == areaCodes[x])
{
***double total = numberOfMinutes * perMinuteRate;***
Console.WriteLine("You call to {0} will cost {1} per minute for a total of {2}.", areaCodes[x], perMinuteRate[x].ToString("C"), total.ToString("C"));
x = areaCodes.Length;
}
}
if (x != areaCodes.Length)
{
Console.WriteLine("I'm sorry; we don't cover that area.");
inputString = "1";
}
else
{
Console.WriteLine("Thanks for being our customer.");
inputString = "0";
}
Console.ReadLine();
}
}
Thank you in advance.
Change:
double total = numberOfMinutes * perMinuteRate;
to
double total = (double)(numberOfMinutes * perMinuteRate[x]);
The same way you index into perMinuteRate in the line directly below.
The expression [int] * [decimal] will result in a decimal, and the cast (double) will convert it to a double
To avoid loss of precision, change it to:
decimal total = numberOfMinutes * perMinuteRate[x];
I am attempting to manually convert numbers between decimal and hexadecimal. I have it working for positive numbers and converting a negative decimal to 'negative' hexadecimal but I can't convert it from 'negative' hexadecimal to negative decimal.
Here is the code I am attempting to work with:
private string HexToDecimal(char[] toConvert)
{
if (negativeValue)
{
negativeValue = false;
long var = Convert.ToInt64(HexToDecimal(ResultLabel.Text.ToCharArray()));
long valueToHex = var - (long)Math.Pow(16, 15);
return ResultLabel.Text = valueToHex.ToString();
}
else
{
double total = 0;
//Convert hex to decimal
HexOrDecimalLabel.Text = "Decimal";
//TODO: create int array from indivial int
char[] charArray = toConvert;
long[] numberArray = HexSwitchFunction(charArray);
//TODO: reverse array
Array.Reverse(numberArray);
//loop array, times value by 16^i++, adding to total. This is the method used to convert hex to decimal
double power = 0;
foreach (int i in numberArray)
{
total += (i * (Math.Pow(16, power)));
power++;
}
//set the result label to total
isHex = false;
AllowHexButtons();
return ResultLabel.Text = total.ToString();
}
}
For instance, I can turn - 10 into FFFFFFFFFFFFFFF6, but when i attempt to turn that into decimal, I get 1.15292150460685E+18, which I can't do any equations with.
Does anyone know of a way around this?
This is because double uses a different representation for negative numbers. Changing the type of total and power from double to long will fix the problem.
It's a little more complicated than that, but this is my code:
private void button1_Click(object sender, EventArgs e)
{
Decimal num1 = Convert.ToDecimal(textBox1.Text);
Decimal num2 = Convert.ToDecimal(textBox2.Text);
Decimal total = num1 + num2;
textBox3.Text = total.ToString("C");
Decimal total2 = Convert.ToDecimal(total);
total2 = total * 4.2;
textBox4.Text = Convert.ToString(total2);
Basically it's this: I have 4 text boxes, and I want to be able to put in a number in box1 and box2. Box three will multiply box 1 & 2 and convert it to currency. Box four will take Box 3s value and change it back to decimal and multiply a number. I can get it to work as long as total2 does not have a decimal. When it has one it will fail.
The program is basically a cash register program that you put in the following:
QTY (box 1)
Amonunt (box 2)
Subtotal (box 3)
Total (box 4)
Any ideas will be helpful.
Thanks,
Caleb
If I understand the problem correctly you perform operations on decimal variables holding currency values. Often it means maintaining a specific resolution (e.g 2 digits after decimal point for cents). Since Decimal is a general purpose type you need to maintain the required resolution programmatically.
example:
static Decimal RoundToCents(Decimal value)
{
return Math.Round(value, 2, MidpointRounding.AwayFromZero);
}
Decimal num1 = RoundToCents(Convert.ToDecimal(textBox1.Text));
Decimal num2 = RoundToCents(Convert.ToDecimal(textBox2.Text));
Decimal total = num1 + num2; // no rounding is needed for additions and subtractions
Decimal total2 = RoundToCents(total * 4.2m);
The fundamental problem is that you are mixing decimal and double in this line:
total2 = total * 4.2;
total is decimal and 4.2 is a double literal. To write a decimal literal use the m suffix.
total2 = total * 4.2m;
All began with these simple lines of code:
string s = "16.9";
double d = Convert.ToDouble(s);
d*=100;
The result should be 1690.0, but it's not. d is equal to 1689.9999999999998.
All I want to do is to round a double to value with 2 digit after decimal separator.
Here is my function.
private double RoundFloat(double Value)
{
float sign = (Value < 0) ? -0.01f : 0.01f;
if (Math.Abs(Value) < 0.00001) Value = 0;
string SVal = Value.ToString();
string DecimalSeparator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;
int i = SVal.IndexOf(DecimalSeparator);
if (i > 0)
{
int SRnd;
try
{
// вземи втората цифра след десетичния разделител
SRnd = Convert.ToInt32(SVal.Substring(i + 3, 1));
}
catch
{
SRnd = 0;
}
if (SVal.Length > i + 3)
SVal = SVal.Substring(0, i + 3);
//SVal += "00001";
try
{
double result = (SRnd >= 5) ? Convert.ToDouble(SVal) + sign : Convert.ToDouble(SVal);
//result = Math.Round(result, 2);
return result;
}
catch
{
return 0;
}
}
else
{
return Value;
}
But again the same problem, converting from string to double is not working as I want.
A workaround to this problem is to concatenate "00001" to the string and then use the Math.Round function (commented in the example above).
This double value multiplied to 100 (as integer) is send to a device (cash register) and this values must be correct.
I am using VS2005 + .NET CF 2.0
Is there another more "elegant" solution, I am not happy with this one.
Doubles can't exactly represent 16.9. I suggest you convert it to decimal instead:
string s = "16.9";
decimal m = Decimal.Parse(s) * 100;
double d = (double)m;
You might just want to keep using the decimal instead of the double, since you say you'll be using it for monetary purposes. Remember that decimal is intended to exactly represent decimal numbers that fit in its precision, while double will only exactly represent binary numbers that do.
Math.Round(number, 1)
Edit I got the wrong question - the rounding problems are inherent to a floating point type (float, double). You should use decimal for this.
The best solution for not going be crazy is:
string s = "16.9";
For ,/.
double d = Convert.ToDouble(s.Replace(',','.'),System.Globalization.CultureInfo.InvariantCulture);
For rounding:
Convert.ToDouble((d).ToString("F2"));