Divide two decimals and cast result to int - c#

I'm trying to cast the result of a divide result to an int in c#
This is my code:
decimal testDecimal = 5.00; // testDecimal always is dividable by 0.25 with 0 rest
int times=0;
int times = testDecimal / Convert.ToDecimal(0.250);
// error returned -> Cannot implicitly convert type 'decimal' to 'int'.
if I change my cast to
int times = (int) testDecimal / Convert.ToDecimal(0.250);
//also returns an error: Cannot implicitly convert type 'decimal' to 'int'
How could I get the result (20) as an integer? What am I doing wrong?

Try this:
times = (int)(testDecimal / Convert.ToDecimal(0.250));
Without the extra parenthesis, it is trying to convert ONLY testDecimal to integer, then trying to convert the int/decimal result to an integer implicitly, which is what causes the error.
In an unrelated note, you are trying to declare the variable 'times' twice.

As everybody answered, you have to add parenthesis to cast the result of the your division instead of just trying to cast the first part and then getting the error after the division.
I also want to point out that it is not necessary to use Convert.ToDecimal just to declare your constant as adecimal, you could use C# suffixs to do so:
int times = (int)(testDecimal / 0.250m);

You have to cast the whole division result. try like:
int times = (int) (testDecimal / Convert.ToDecimal(0.250));
Be careful though because this could suffer the seemingly random floating point arithmetic error depending on which values you use.
https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
You may avoid this by first rounding the value.
(int) Math.Round(testDecimal / Convert.ToDecimal(0.250));

first you don't need to do convert to decimal, you can just do 0.25m
and then you can do
times = (int) (testDecimal / 0.25m);
do note that if the number is too big this might give you wrong result.

If you want a numeric literal to be treated as decimal, use the suffix m or M. By this way there is no need to use Convert.ToDecimal.
decimal testDecimal = 5.00M;
int times = (int)(testDecimal / 0.250M);

First of all you should add "M" suffix to your testDecimal declaration otherwise your 5.00 is a litteral and not a decimal.
decimal testDecimal = 5.00M;
Now, your compiler is not aware that your division result is an integer. Even if your devision can be casted to "int", for him, a decimal devided by another is a decimal and not an integer. You have to implicitly cast it:
int times = (int)(testDecimal / 0.250M);
Works like charm for me.

Wrap your expression in parenthesis so that you can convert it:
// int times = (int)testDecimal / 0.250m;
int times = (int)(testDecimal / 0.250m);
Just a note, make sure you are try/catching while converting because not all decimal values can fit into int.
try
{
times = (int)decimal.MaxValue;
}
catch(OverflowException ex)
{
// Value was either too large or too small for an Int32.
}

I'm not sure why you have Convert.ToDecimal(0.250). Why convert the float (0.250) to a decimal at run time? Why not just use a decimal literal (like 0.25M)? As other folks have noted, you need to cast the results of the division to an int, like:
decimal testDecimal = 5M;
int times = (int) (testDecimal / 0.25M);
Assert.AreEqual(20, times);
Also, as other folks have noted, you may want to think through how you do your conversion from decimal to int. Do you want to the default behavior (what you get from a simple cast), or do you want round up, round down, round to even, etc.? In this case, since the division yields an integral result, it doesn't matter, but in the general case, you'll want to put some thought into it.
By the way, the reason you have an error in this code:
int times = (int) testDecimal / Convert.ToDecimal(0.250);
is that you are casting testDecimal (5.0M) to an int (5). Then you are dividing it by a decimal (0.25M), which yields a decimal (20.0M). Finally, you are trying to assign that decimal to an integer, and the compiler signals an error.
HTH

Related

Math.Round() while casting and calculating returning wrong result

I was just curious if anyone could explain to me why these different data types round differently in my code? (note: this is not how the variables are actually declared, it is how they are stored. I just displayed them like this for clarity)
double amount = 15 ;
double taxPercentage = 0.015;
decimal itemTax;
First, the un-rounded result:
itemTax = (decimal)(amount * taxPercentage);
// itemTax returns -0.225
If I round first, then cast to decimal:
itemTax = (decimal)(Math.Round(amount * taxPercentage, 2, MidpointRounding.AwayFromZero));
// itemTax returns -0.22
If I cast to decimal first, then round:
itemTax = (decimal)(amount * taxPercentage);
itemTax = Math.Round(itemTax,2,MidpointRounding.AwayFromZero);
// itemTax returns -0.23
Does this have something to do with the way double types round vs. decimal types?
Indeed. Double (like float) is base-2 number and is actually an approximation of a decimal value. Unlike decimal values, it can't represent infinite precision numbers so your -0.025 values might really be -0.024999999999

Convert Object to int without rounding

I have to convert an object to int. My object values is something like 1.34535
What I need is the first part which is (1).
I tried the followings:
- Convert.ToInt32(myObj.Value), it rounds the number. if it's 1.78, I got it (2) which is wrong. I need only the integer of first part.
int.TryParse(myObj.Value.toString(), out outValue)
I got it 0 for all values!
int.Parse(myObj.Value.toString()) throws an exception, that is in incorrect format.
If myObj.Value is boxed double then you have to cast twice: to unbox back into double and then in order to truncate into int:
int result = (int)((double)(myObj.Value)):
In general case, try Convert; the idea is the same: first restore the orignal double and then obtain required int:
int result = (int) (Convert.ToDouble(myObj.Value));
Edit: in the implementation above I've read without rounding request as truncated, i.e. fractional part should be ignored:
2.4 -> 2
-2.4 -> -2
If different behaviour is expected, e.g.
2.4 -> 2
-2.4 -> -3
one can add Math.Floor e.g.
int result = (int) (Math.Floor(Convert.ToDouble(myObj.Value)));
Convert to double it first;
var doubleValue = double.Parse(myObj.Value.ToString());
//It could be better to use double.TryParse
int myInt = (int)Math.Floor(doubleValue);
Convert your object to a double value and use Use Math.Truncate(number)
http://msdn.microsoft.com/en-us/library/c2eabd70.aspx
Very easy, don't forget to wrap it in try and catch:
int i = (int)Math.Truncate(double.Parse(myObj.ToString()));
Math.Truncate just cuts off the numbers after the comma like:
4.434 becomes 4
-43.65445 becomes -43
Perhaps, this is also a solution :
var integer = int.Parse(myObject.Value.ToString().Split('.').First());

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;

Subtract percentage in C#

I'm trying to subtract percentage in C# using:
n = n - (n * 0.25);
but I'm getting an error:
"Cannot implicitly 'double' to 'int'. An explicit conversions exists
(are you missing a cast?)"
Your value n is an int.
When you multiply by 0.25( which is a double), the resulting value is a double that you try to assign to a int.
To solve it, you have to specify that you are aware that you will lose precision using "explicit conversion".
n = n - (int)(n * 0.25);
Doing (Type)value is called "to cast value to Type". This is exactly what the error message suggest you to do.
Or, if you don't want to keep the precision, declare n not as an int but as a double. In this case, you will not have to cast n * 0.25 to int.
If you don't want to switch back and forwards between int and double types you could just use:
n = (n * 75) / 100
if your answer ever has decimals they'll be lost though
Your variable n must be an integer, but the result of your calculation is a double, since it involves multiplication by a double (0.25).
You can cast the result back to an int like this:
n = (int)(n - (n * 0.25));
I'm assuming that n is an integer type then, say int, as you don't give a clue to that. In which case the easiest solution is to do:
n = Convert.ToInt32(n - (n * 0.25));
Or you can cast:
n = (int)(n - (n * 0.25));
Check the type of variable 'n'.
Either 'n' should be of double type.
Or
Use explicit cast to convert to int.
int n = (int)(n - (n * 0.25));
you must cast result to int
n=(int)(n-(n*0.25));
try:
n = n - (int)((double)n * 0.25);
note: by doing this you wont have numbers behind the point in the n result.
I guess this could be an issue with the type of n being int it least needs to be double
hence when you have n = n - (n * 0.25) the result is a double
if you want to cast it as int then beware of rounding since it would not always be ending in .00
Also i think this would be better n = n * 0.75
Your n variable is an int. When you try to multiple with 0.25, 0.25 is double, so result will be double. You should cast it manually because there is no Implicit Numeric Conversion for double to int. You have to use Explicit Numeric Conversion for them.
From --> To
double --> sbyte , byte, short, ushort, int, uint, long, ulong, char, float, or decimal
You should convert your right expression to int.
int n = 100;
n = (int) (n - (n * 0.25));
Console.WriteLine(n);
Here is a DEMO.
And remember;
Explicit numeric conversion may cause loss of precision.
When you convert from a double value to an integral type, the value is truncated. If the resulting integral value is outside the range of the destination value, the result depends on the overflow checking context.
The best way would be to do
n = n - n/4;
If you want a percentage to be a whole number between 0 and 100, otherwise you should declare n to be a double by replacing int n with double n.
No costly conversion will occur in the proposed assignment. Note that n/4 is an integer because both operands (n and 4) are integers, causing no promotions, thus using integer division.
Explanation
This is type promotion, n is multiplied by a double, which promotes n*0.25 automatically to a double. A primitive can only be promoted into a higher rank, not demoted to a lower rank. A primitive x is of a higher rank then another primitive y if it can hold all values of y without causing loss of precision. A double can hold all values of an integer, but an integer can, for example, not hold 0.1. So you are trying to promote and demote. See MSDN library for more information.
Note:
Casting from a double to an int causes the value to be truncated, that is all decimals after the 'dot' will be erased, so -2.5 becomes -2 and 1.5 becomes 1. Integer division, as used above also rounds to zero, making this assignment equal with your assignment. But avoiding any costly conversions.

How do you divide integers and get a double in C#?

int x = 73;
int y = 100;
double pct = x/y;
Why do I see 0 instead of .73?
Because the division is done with integers then converted to a double. Try this instead:
double pct = (double)x / (double)y;
It does the same in all C-like languages. If you divide two integers, the result is an integer. 0.73 is not an integer.
The common work-around is to multiply one of the two numbers by 1.0 to make it a floating point type, or just cast it.
because the operation is still on int type. Try double pct = (double)x / (double)y;
Integer division drops the fractional portion of the result. See: http://mathworld.wolfram.com/IntegerDivision.html
It's important to understand the flow of execution in a line of code. You're correct to assume that setting the right side of the equation equal to double (on the left side) will implicitly convert the solution as a double. However, the flow execution dicates that x/y is evaluated by itself before you even get to the double pct = portion of the code. Thus, since two ints are divided by each other, they will evaluate to an int solution (in this case, rounding towards zero) before being implicitly converted to a double.
As other have noted, you'll need to cast the int variables as doubles so the solution comes out as a double and not as an int.
That’s because the type of the left hand operand of the division (x) is of type int, so the return type of x / y is still int. The fact that the destination variable is of type double doesn’t affect the operation.
To get the intended result, you first have to cast (convert) x to double, as in:
double pct = (double)x / y;

Categories

Resources